blob: bb9df3435f92a794bf37d30c2d79852f57cb9923 [file] [log] [blame]
Steve Naroffb29b4272008-04-14 22:03:09 +00001//===--- RewriteObjC.cpp - Playground for the code rewriter ---------------===//
Chris Lattner77cd2a02007-10-11 00:43:27 +00002//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner77cd2a02007-10-11 00:43:27 +00007//
8//===----------------------------------------------------------------------===//
9//
10// Hacks and fun related to the code rewriter.
11//
12//===----------------------------------------------------------------------===//
13
Daniel Dunbar9b414d32010-06-15 17:48:49 +000014#include "clang/Rewrite/ASTConsumers.h"
Chris Lattner8a12c272007-10-11 18:38:32 +000015#include "clang/Rewrite/Rewriter.h"
Chris Lattner77cd2a02007-10-11 00:43:27 +000016#include "clang/AST/AST.h"
17#include "clang/AST/ASTConsumer.h"
Steve Naroff8599e7a2008-12-08 16:43:47 +000018#include "clang/AST/ParentMap.h"
Chris Lattner8a12c272007-10-11 18:38:32 +000019#include "clang/Basic/SourceManager.h"
Steve Naroffebf2b562007-10-23 23:50:29 +000020#include "clang/Basic/IdentifierTable.h"
Chris Lattner07506182007-11-30 22:53:43 +000021#include "clang/Basic/Diagnostic.h"
Chris Lattner26de4652007-12-02 01:13:47 +000022#include "clang/Lex/Lexer.h"
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +000023#include "llvm/Support/MemoryBuffer.h"
24#include "llvm/Support/raw_ostream.h"
Chris Lattner158ecb92007-10-25 17:07:24 +000025#include "llvm/ADT/StringExtras.h"
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +000026#include "llvm/ADT/SmallPtrSet.h"
Ted Kremeneka95d3752008-09-13 05:16:45 +000027#include "llvm/ADT/OwningPtr.h"
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +000028#include "llvm/ADT/DenseSet.h"
Fariborz Jahanian72952fc2010-03-01 23:36:21 +000029
Chris Lattner77cd2a02007-10-11 00:43:27 +000030using namespace clang;
Chris Lattner158ecb92007-10-25 17:07:24 +000031using llvm::utostr;
Chris Lattner77cd2a02007-10-11 00:43:27 +000032
Chris Lattner77cd2a02007-10-11 00:43:27 +000033namespace {
Steve Naroffb29b4272008-04-14 22:03:09 +000034 class RewriteObjC : public ASTConsumer {
Fariborz Jahanian73e437b2009-12-23 21:18:41 +000035 enum {
Nico Weber59b173d2010-11-22 10:26:41 +000036 BLOCK_FIELD_IS_OBJECT = 3, /* id, NSObject, __attribute__((NSObject)),
Fariborz Jahanian73e437b2009-12-23 21:18:41 +000037 block, ... */
38 BLOCK_FIELD_IS_BLOCK = 7, /* a block variable */
39 BLOCK_FIELD_IS_BYREF = 8, /* the on stack structure holding the
40 __block variable */
Nico Weber59b173d2010-11-22 10:26:41 +000041 BLOCK_FIELD_IS_WEAK = 16, /* declared __weak, only used in byref copy
Fariborz Jahanian73e437b2009-12-23 21:18:41 +000042 helpers */
Nico Weber59b173d2010-11-22 10:26:41 +000043 BLOCK_BYREF_CALLER = 128, /* called from __block (byref) copy/dispose
Fariborz Jahanian73e437b2009-12-23 21:18:41 +000044 support routines */
45 BLOCK_BYREF_CURRENT_MAX = 256
46 };
47
48 enum {
49 BLOCK_NEEDS_FREE = (1 << 24),
50 BLOCK_HAS_COPY_DISPOSE = (1 << 25),
51 BLOCK_HAS_CXX_OBJ = (1 << 26),
52 BLOCK_IS_GC = (1 << 27),
53 BLOCK_IS_GLOBAL = (1 << 28),
54 BLOCK_HAS_DESCRIPTOR = (1 << 29)
55 };
Fariborz Jahanian58457172011-12-05 18:43:13 +000056 static const int OBJC_ABI_VERSION = 7;
Fariborz Jahanian73e437b2009-12-23 21:18:41 +000057
Chris Lattner2c64b7b2007-10-16 21:07:07 +000058 Rewriter Rewrite;
David Blaikied6471f72011-09-25 23:23:43 +000059 DiagnosticsEngine &Diags;
Steve Naroff4f943c22008-03-10 20:43:59 +000060 const LangOptions &LangOpts;
Steve Narofff69cc5d2008-01-30 19:17:43 +000061 unsigned RewriteFailedDiag;
Steve Naroff8c565152008-12-05 17:03:39 +000062 unsigned TryFinallyContainsReturnDiag;
Mike Stump1eb44332009-09-09 15:08:12 +000063
Chris Lattner01c57482007-10-17 22:35:30 +000064 ASTContext *Context;
Chris Lattner77cd2a02007-10-11 00:43:27 +000065 SourceManager *SM;
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +000066 TranslationUnitDecl *TUDecl;
Chris Lattner2b2453a2009-01-17 06:22:33 +000067 FileID MainFileID;
Chris Lattner26de4652007-12-02 01:13:47 +000068 const char *MainFileStart, *MainFileEnd;
Fariborz Jahanian58457172011-12-05 18:43:13 +000069 Stmt *CurrentBody;
70 ParentMap *PropParentMap; // created lazily.
71
Chris Lattner2c64b7b2007-10-16 21:07:07 +000072 SourceLocation LastIncLoc;
Mike Stump1eb44332009-09-09 15:08:12 +000073
Chris Lattner5f9e2722011-07-23 10:55:15 +000074 SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
75 SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
Ted Kremeneka526c5c2008-01-07 19:49:32 +000076 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs;
Steve Narofffbfe8252008-05-06 18:26:51 +000077 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> ObjCSynthesizedProtocols;
Ted Kremeneka526c5c2008-01-07 19:49:32 +000078 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCForwardDecls;
79 llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
Chris Lattner5f9e2722011-07-23 10:55:15 +000080 SmallVector<Stmt *, 32> Stmts;
81 SmallVector<int, 8> ObjCBcLabelNo;
Steve Naroff621edce2009-04-29 16:37:50 +000082 // Remember all the @protocol(<expr>) expressions.
83 llvm::SmallPtrSet<ObjCProtocolDecl *, 32> ProtocolExprDecls;
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +000084
85 llvm::DenseSet<uint64_t> CopyDestroyCache;
86
Steve Naroffd82a9ab2008-03-15 00:55:56 +000087 unsigned NumObjCStringLiterals;
Mike Stump1eb44332009-09-09 15:08:12 +000088
Steve Naroffebf2b562007-10-23 23:50:29 +000089 FunctionDecl *MsgSendFunctionDecl;
Steve Naroff874e2322007-11-15 10:28:18 +000090 FunctionDecl *MsgSendSuperFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +000091 FunctionDecl *MsgSendStretFunctionDecl;
92 FunctionDecl *MsgSendSuperStretFunctionDecl;
Fariborz Jahanianacb49772007-12-03 21:26:48 +000093 FunctionDecl *MsgSendFpretFunctionDecl;
Steve Naroffebf2b562007-10-23 23:50:29 +000094 FunctionDecl *GetClassFunctionDecl;
Steve Naroff9bcb5fc2007-12-07 03:50:46 +000095 FunctionDecl *GetMetaClassFunctionDecl;
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +000096 FunctionDecl *GetSuperClassFunctionDecl;
Steve Naroff934f2762007-10-24 22:48:43 +000097 FunctionDecl *SelGetUidFunctionDecl;
Steve Naroff96984642007-11-08 14:30:50 +000098 FunctionDecl *CFStringFunctionDecl;
Steve Naroffc0a123c2008-03-11 17:37:02 +000099 FunctionDecl *SuperContructorFunctionDecl;
Mike Stump1eb44332009-09-09 15:08:12 +0000100
Steve Naroffbeaf2992007-11-03 11:27:19 +0000101 // ObjC string constant support.
Steve Naroff248a7532008-04-15 22:42:06 +0000102 VarDecl *ConstantStringClassReference;
Steve Naroffbeaf2992007-11-03 11:27:19 +0000103 RecordDecl *NSStringRecord;
Mike Stump1eb44332009-09-09 15:08:12 +0000104
Fariborz Jahanianb586cce2008-01-16 00:09:11 +0000105 // ObjC foreach break/continue generation support.
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000106 int BcLabelCount;
Mike Stump1eb44332009-09-09 15:08:12 +0000107
Steve Naroff874e2322007-11-15 10:28:18 +0000108 // Needed for super.
Steve Naroff54055232008-10-27 17:20:55 +0000109 ObjCMethodDecl *CurMethodDef;
Steve Naroff874e2322007-11-15 10:28:18 +0000110 RecordDecl *SuperStructDecl;
Steve Naroffd82a9ab2008-03-15 00:55:56 +0000111 RecordDecl *ConstantStringDecl;
Mike Stump1eb44332009-09-09 15:08:12 +0000112
Steve Naroff621edce2009-04-29 16:37:50 +0000113 TypeDecl *ProtocolTypeDecl;
114 QualType getProtocolType();
Mike Stump1eb44332009-09-09 15:08:12 +0000115
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000116 // Needed for header files being rewritten
117 bool IsHeader;
Mike Stump1eb44332009-09-09 15:08:12 +0000118
Steve Naroffa7b402d2008-03-28 22:26:09 +0000119 std::string InFileName;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000120 raw_ostream* OutFile;
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000121
122 bool SilenceRewriteMacroWarning;
Fariborz Jahanianf292fcf2010-01-07 22:51:18 +0000123 bool objc_impl_method;
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000124
Steve Naroffba92b2e2008-03-27 22:29:16 +0000125 std::string Preamble;
Steve Naroff54055232008-10-27 17:20:55 +0000126
127 // Block expressions.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000128 SmallVector<BlockExpr *, 32> Blocks;
129 SmallVector<int, 32> InnerDeclRefsCount;
130 SmallVector<BlockDeclRefExpr *, 32> InnerDeclRefs;
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +0000131
Chris Lattner5f9e2722011-07-23 10:55:15 +0000132 SmallVector<BlockDeclRefExpr *, 32> BlockDeclRefs;
Mike Stump1eb44332009-09-09 15:08:12 +0000133
Steve Naroff54055232008-10-27 17:20:55 +0000134 // Block related declarations.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000135 SmallVector<ValueDecl *, 8> BlockByCopyDecls;
Fariborz Jahanianbab71682010-02-11 23:35:57 +0000136 llvm::SmallPtrSet<ValueDecl *, 8> BlockByCopyDeclsPtrSet;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000137 SmallVector<ValueDecl *, 8> BlockByRefDecls;
Fariborz Jahanianbab71682010-02-11 23:35:57 +0000138 llvm::SmallPtrSet<ValueDecl *, 8> BlockByRefDeclsPtrSet;
Fariborz Jahaniana73165e2010-01-14 23:05:52 +0000139 llvm::DenseMap<ValueDecl *, unsigned> BlockByRefDeclNo;
Steve Naroff54055232008-10-27 17:20:55 +0000140 llvm::SmallPtrSet<ValueDecl *, 8> ImportedBlockDecls;
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +0000141 llvm::SmallPtrSet<VarDecl *, 8> ImportedLocalExternalDecls;
142
Steve Naroff54055232008-10-27 17:20:55 +0000143 llvm::DenseMap<BlockExpr *, std::string> RewrittenBlockExprs;
144
Steve Naroff4c3580e2008-12-04 23:50:32 +0000145 // This maps an original source AST to it's rewritten form. This allows
146 // us to avoid rewriting the same node twice (which is very uncommon).
147 // This is needed to support some of the exotic property rewriting.
148 llvm::DenseMap<Stmt *, Stmt *> ReplacedNodes;
Steve Naroff15f081d2008-12-03 00:56:33 +0000149
Steve Naroff54055232008-10-27 17:20:55 +0000150 FunctionDecl *CurFunctionDef;
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +0000151 FunctionDecl *CurFunctionDeclToDeclareForBlock;
Steve Naroff8e2f57a2008-10-29 18:15:37 +0000152 VarDecl *GlobalVarDecl;
Mike Stump1eb44332009-09-09 15:08:12 +0000153
Steve Naroffb619d952008-12-09 12:56:34 +0000154 bool DisableReplaceStmt;
John McCall4b9c2d22011-11-06 09:01:30 +0000155 class DisableReplaceStmtScope {
156 RewriteObjC &R;
157 bool SavedValue;
Fariborz Jahanian58457172011-12-05 18:43:13 +0000158
John McCall4b9c2d22011-11-06 09:01:30 +0000159 public:
160 DisableReplaceStmtScope(RewriteObjC &R)
161 : R(R), SavedValue(R.DisableReplaceStmt) {
162 R.DisableReplaceStmt = true;
163 }
164 ~DisableReplaceStmtScope() {
165 R.DisableReplaceStmt = SavedValue;
166 }
167 };
Mike Stump1eb44332009-09-09 15:08:12 +0000168
Chris Lattner77cd2a02007-10-11 00:43:27 +0000169 public:
Ted Kremeneke3a61982008-05-31 20:11:04 +0000170 virtual void Initialize(ASTContext &context);
171
Chris Lattnerf04da132007-10-24 17:06:59 +0000172 // Top Level Driver code.
Argyrios Kyrtzidis88c25962011-11-18 00:26:59 +0000173 virtual bool HandleTopLevelDecl(DeclGroupRef D) {
Fariborz Jahanian95ed7782011-08-27 20:50:59 +0000174 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
175 if (isa<ObjCClassDecl>((*I))) {
176 RewriteForwardClassDecl(D);
177 break;
178 }
Chris Lattner682bf922009-03-29 16:50:03 +0000179 HandleTopLevelSingleDecl(*I);
Fariborz Jahanian95ed7782011-08-27 20:50:59 +0000180 }
Argyrios Kyrtzidis88c25962011-11-18 00:26:59 +0000181 return true;
Chris Lattner682bf922009-03-29 16:50:03 +0000182 }
183 void HandleTopLevelSingleDecl(Decl *D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000184 void HandleDeclInMainFile(Decl *D);
Chris Lattner5f9e2722011-07-23 10:55:15 +0000185 RewriteObjC(std::string inFile, raw_ostream *OS,
David Blaikied6471f72011-09-25 23:23:43 +0000186 DiagnosticsEngine &D, const LangOptions &LOpts,
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000187 bool silenceMacroWarn);
Ted Kremeneke452e0f2008-08-08 04:15:52 +0000188
189 ~RewriteObjC() {}
Mike Stump1eb44332009-09-09 15:08:12 +0000190
Chris Lattnerdacbc5d2009-03-28 04:11:33 +0000191 virtual void HandleTranslationUnit(ASTContext &C);
Mike Stump1eb44332009-09-09 15:08:12 +0000192
Fariborz Jahanian88906cd2010-02-05 16:43:40 +0000193 void ReplaceStmt(Stmt *Old, Stmt *New) {
Steve Naroff4c3580e2008-12-04 23:50:32 +0000194 Stmt *ReplacingStmt = ReplacedNodes[Old];
Mike Stump1eb44332009-09-09 15:08:12 +0000195
Steve Naroff4c3580e2008-12-04 23:50:32 +0000196 if (ReplacingStmt)
197 return; // We can't rewrite the same node twice.
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000198
Steve Naroffb619d952008-12-09 12:56:34 +0000199 if (DisableReplaceStmt)
John McCall4b9c2d22011-11-06 09:01:30 +0000200 return;
Steve Naroffb619d952008-12-09 12:56:34 +0000201
Steve Naroff4c3580e2008-12-04 23:50:32 +0000202 // If replacement succeeded or warning disabled return with no warning.
Fariborz Jahanian88906cd2010-02-05 16:43:40 +0000203 if (!Rewrite.ReplaceStmt(Old, New)) {
Steve Naroff4c3580e2008-12-04 23:50:32 +0000204 ReplacedNodes[Old] = New;
205 return;
206 }
207 if (SilenceRewriteMacroWarning)
208 return;
Chris Lattner0a14eee2008-11-18 07:04:44 +0000209 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
210 << Old->getSourceRange();
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000211 }
Steve Naroffb619d952008-12-09 12:56:34 +0000212
213 void ReplaceStmtWithRange(Stmt *Old, Stmt *New, SourceRange SrcRange) {
John McCall4b9c2d22011-11-06 09:01:30 +0000214 if (DisableReplaceStmt)
215 return;
216
Nick Lewycky7e749242010-10-31 21:07:24 +0000217 // Measure the old text.
Steve Naroffb619d952008-12-09 12:56:34 +0000218 int Size = Rewrite.getRangeSize(SrcRange);
219 if (Size == -1) {
220 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
221 << Old->getSourceRange();
222 return;
223 }
224 // Get the new text.
225 std::string SStr;
226 llvm::raw_string_ostream S(SStr);
Chris Lattnere4f21422009-06-30 01:26:17 +0000227 New->printPretty(S, *Context, 0, PrintingPolicy(LangOpts));
Steve Naroffb619d952008-12-09 12:56:34 +0000228 const std::string &Str = S.str();
229
230 // If replacement succeeded or warning disabled return with no warning.
Daniel Dunbard7407dc2009-08-19 19:10:30 +0000231 if (!Rewrite.ReplaceText(SrcRange.getBegin(), Size, Str)) {
Steve Naroffb619d952008-12-09 12:56:34 +0000232 ReplacedNodes[Old] = New;
233 return;
234 }
235 if (SilenceRewriteMacroWarning)
236 return;
237 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
238 << Old->getSourceRange();
239 }
240
Chris Lattner5f9e2722011-07-23 10:55:15 +0000241 void InsertText(SourceLocation Loc, StringRef Str,
Steve Naroffba92b2e2008-03-27 22:29:16 +0000242 bool InsertAfter = true) {
Chris Lattneraadaf782008-01-31 19:51:04 +0000243 // If insertion succeeded or warning disabled return with no warning.
Benjamin Kramerd999b372010-02-14 14:14:16 +0000244 if (!Rewrite.InsertText(Loc, Str, InsertAfter) ||
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000245 SilenceRewriteMacroWarning)
246 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000247
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000248 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
249 }
Mike Stump1eb44332009-09-09 15:08:12 +0000250
Chris Lattneraadaf782008-01-31 19:51:04 +0000251 void ReplaceText(SourceLocation Start, unsigned OrigLength,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000252 StringRef Str) {
Chris Lattneraadaf782008-01-31 19:51:04 +0000253 // If removal succeeded or warning disabled return with no warning.
Benjamin Kramerd999b372010-02-14 14:14:16 +0000254 if (!Rewrite.ReplaceText(Start, OrigLength, Str) ||
Chris Lattneraadaf782008-01-31 19:51:04 +0000255 SilenceRewriteMacroWarning)
256 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000257
Chris Lattneraadaf782008-01-31 19:51:04 +0000258 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
259 }
Mike Stump1eb44332009-09-09 15:08:12 +0000260
Chris Lattnerf04da132007-10-24 17:06:59 +0000261 // Syntactic Rewriting.
Fariborz Jahanian58457172011-12-05 18:43:13 +0000262 void RewriteRecordBody(RecordDecl *RD);
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000263 void RewriteInclude();
Fariborz Jahanian95ed7782011-08-27 20:50:59 +0000264 void RewriteForwardClassDecl(DeclGroupRef D);
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000265 void RewriteForwardClassDecl(const llvm::SmallVector<Decl*, 8> &DG);
266 void RewriteForwardClassEpilogue(ObjCClassDecl *ClassDecl,
267 const std::string &typedefString);
Fariborz Jahanian58457172011-12-05 18:43:13 +0000268 void RewriteImplementations();
Steve Naroffa0876e82008-12-02 17:36:43 +0000269 void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
270 ObjCImplementationDecl *IMD,
271 ObjCCategoryImplDecl *CID);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000272 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000273 void RewriteImplementationDecl(Decl *Dcl);
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +0000274 void RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
275 ObjCMethodDecl *MDecl, std::string &ResultStr);
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000276 void RewriteTypeIntoString(QualType T, std::string &ResultStr,
277 const FunctionType *&FPRetType);
Fariborz Jahaniana73165e2010-01-14 23:05:52 +0000278 void RewriteByRefString(std::string &ResultStr, const std::string &Name,
Fariborz Jahanian1e8011e2011-01-27 23:18:15 +0000279 ValueDecl *VD, bool def=false);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000280 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
281 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
282 void RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *Dcl);
283 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
Steve Naroff6327e0d2009-01-11 01:06:09 +0000284 void RewriteProperty(ObjCPropertyDecl *prop);
Steve Naroff09b266e2007-10-30 23:14:51 +0000285 void RewriteFunctionDecl(FunctionDecl *FD);
Daniel Dunbarfa297fb2010-06-30 19:16:53 +0000286 void RewriteBlockPointerType(std::string& Str, QualType Type);
287 void RewriteBlockPointerTypeVariable(std::string& Str, ValueDecl *VD);
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +0000288 void RewriteBlockLiteralFunctionDecl(FunctionDecl *FD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000289 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +0000290 void RewriteTypeOfDecl(VarDecl *VD);
Steve Naroff4f95b752008-07-29 18:15:38 +0000291 void RewriteObjCQualifiedInterfaceTypes(Expr *E);
Fariborz Jahanian58457172011-12-05 18:43:13 +0000292
Chris Lattnerf04da132007-10-24 17:06:59 +0000293 // Expression Rewriting.
Steve Narofff3473a72007-11-09 15:20:18 +0000294 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
Chris Lattnere64b7772007-10-24 16:57:36 +0000295 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
John McCall4b9c2d22011-11-06 09:01:30 +0000296 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV);
297 Stmt *RewritePropertyOrImplicitGetter(PseudoObjectExpr *Pseudo);
298 Stmt *RewritePropertyOrImplicitSetter(PseudoObjectExpr *Pseudo);
Steve Naroffb42f8412007-11-05 14:50:49 +0000299 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattnere64b7772007-10-24 16:57:36 +0000300 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000301 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000302 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Steve Naroffb85e77a2009-12-05 21:43:12 +0000303 void RewriteTryReturnStmts(Stmt *S);
304 void RewriteSyncReturnStmts(Stmt *S, std::string buf);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000305 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +0000306 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000307 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
Chris Lattner338d1e22008-01-31 05:10:40 +0000308 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
309 SourceLocation OrigEnd);
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000310 Stmt *RewriteBreakStmt(BreakStmt *S);
311 Stmt *RewriteContinueStmt(ContinueStmt *S);
Fariborz Jahanian58457172011-12-05 18:43:13 +0000312 void RewriteCastExpr(CStyleCastExpr *CE);
Mike Stump1eb44332009-09-09 15:08:12 +0000313
Fariborz Jahanian58457172011-12-05 18:43:13 +0000314 // Metadata Rewriting.
315 void RewriteMetaDataIntoBuffer(std::string &Result);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000316 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000317 std::string &Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000318
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000319 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000320 std::string &Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000321
Douglas Gregor653f1b12009-04-23 01:02:12 +0000322 template<typename MethodIterator>
323 void RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
324 MethodIterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +0000325 bool IsInstanceMethod,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000326 StringRef prefix,
327 StringRef ClassName,
Chris Lattner158ecb92007-10-25 17:07:24 +0000328 std::string &Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000329
Steve Naroff621edce2009-04-29 16:37:50 +0000330 void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000331 StringRef prefix,
332 StringRef ClassName,
Steve Naroff621edce2009-04-29 16:37:50 +0000333 std::string &Result);
334 void RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Prots,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000335 StringRef prefix,
336 StringRef ClassName,
Steve Naroff621edce2009-04-29 16:37:50 +0000337 std::string &Result);
Steve Naroff54055232008-10-27 17:20:55 +0000338 // Block rewriting.
Mike Stump1eb44332009-09-09 15:08:12 +0000339 void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D);
Fariborz Jahanian58457172011-12-05 18:43:13 +0000340
Mike Stump1eb44332009-09-09 15:08:12 +0000341 // Block specific rewrite rules.
Steve Naroff54055232008-10-27 17:20:55 +0000342 void RewriteBlockPointerDecl(NamedDecl *VD);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +0000343 void RewriteByRefVar(VarDecl *VD);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +0000344 Stmt *RewriteBlockDeclRefExpr(Expr *VD);
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +0000345 Stmt *RewriteLocalVariableExternalStorage(DeclRefExpr *DRE);
Steve Naroff54055232008-10-27 17:20:55 +0000346 void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
Fariborz Jahanian58457172011-12-05 18:43:13 +0000347
348 void RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
349 std::string &Result);
350 void RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
351 std::string &Result);
352
353 // Misc. AST transformation routines. Somtimes they end up calling
354 // rewriting routines on the new ASTs.
355 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
356 Expr **args, unsigned nargs,
357 SourceLocation StartLoc=SourceLocation(),
358 SourceLocation EndLoc=SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +0000359
Fariborz Jahanian58457172011-12-05 18:43:13 +0000360 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp,
361 SourceLocation StartLoc=SourceLocation(),
362 SourceLocation EndLoc=SourceLocation());
363
364 void SynthCountByEnumWithState(std::string &buf);
365 void SynthMsgSendFunctionDecl();
366 void SynthMsgSendSuperFunctionDecl();
367 void SynthMsgSendStretFunctionDecl();
368 void SynthMsgSendFpretFunctionDecl();
369 void SynthMsgSendSuperStretFunctionDecl();
370 void SynthGetClassFunctionDecl();
371 void SynthGetMetaClassFunctionDecl();
372 void SynthGetSuperClassFunctionDecl();
373 void SynthSelGetUidFunctionDecl();
374 void SynthSuperContructorFunctionDecl();
375
376 std::string SynthesizeByrefCopyDestroyHelper(VarDecl *VD, int flag);
Mike Stump1eb44332009-09-09 15:08:12 +0000377 std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000378 StringRef funcName, std::string Tag);
Mike Stump1eb44332009-09-09 15:08:12 +0000379 std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000380 StringRef funcName, std::string Tag);
Steve Naroff01aec112009-12-06 21:14:13 +0000381 std::string SynthesizeBlockImpl(BlockExpr *CE,
382 std::string Tag, std::string Desc);
383 std::string SynthesizeBlockDescriptor(std::string DescTag,
384 std::string ImplTag,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000385 int i, StringRef funcName,
Steve Naroff01aec112009-12-06 21:14:13 +0000386 unsigned hasCopy);
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +0000387 Stmt *SynthesizeBlockCall(CallExpr *Exp, const Expr* BlockExp);
Steve Naroff54055232008-10-27 17:20:55 +0000388 void SynthesizeBlockLiterals(SourceLocation FunLocStart,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000389 StringRef FunName);
Fariborz Jahanian58457172011-12-05 18:43:13 +0000390 FunctionDecl *SynthBlockInitFunctionDecl(StringRef name);
391 Stmt *SynthBlockInitExpr(BlockExpr *Exp,
392 const SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs);
Mike Stump1eb44332009-09-09 15:08:12 +0000393
Fariborz Jahanian58457172011-12-05 18:43:13 +0000394 // Misc. helper routines.
395 void WarnAboutReturnGotoStmts(Stmt *S);
396 void HasReturnStmts(Stmt *S, bool &hasReturns);
397 void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
398 void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
399 void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
400
401 bool IsDeclStmtInForeachHeader(DeclStmt *DS);
Steve Naroff54055232008-10-27 17:20:55 +0000402 void CollectBlockDeclRefInfo(BlockExpr *Exp);
Steve Naroff54055232008-10-27 17:20:55 +0000403 void GetBlockDeclRefExprs(Stmt *S);
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +0000404 void GetInnerBlockDeclRefExprs(Stmt *S,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000405 SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs,
Fariborz Jahanian72952fc2010-03-01 23:36:21 +0000406 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts);
Mike Stump1eb44332009-09-09 15:08:12 +0000407
Steve Naroff54055232008-10-27 17:20:55 +0000408 // We avoid calling Type::isBlockPointerType(), since it operates on the
409 // canonical type. We only care if the top-level type is a closure pointer.
Ted Kremenek8189cde2009-02-07 01:47:29 +0000410 bool isTopLevelBlockPointerType(QualType T) {
411 return isa<BlockPointerType>(T);
412 }
Mike Stump1eb44332009-09-09 15:08:12 +0000413
Fariborz Jahanian4fc84532010-05-25 17:12:52 +0000414 /// convertBlockPointerToFunctionPointer - Converts a block-pointer type
415 /// to a function pointer type and upon success, returns true; false
416 /// otherwise.
417 bool convertBlockPointerToFunctionPointer(QualType &T) {
418 if (isTopLevelBlockPointerType(T)) {
419 const BlockPointerType *BPT = T->getAs<BlockPointerType>();
420 T = Context->getPointerType(BPT->getPointeeType());
421 return true;
422 }
423 return false;
424 }
425
Fariborz Jahanian58457172011-12-05 18:43:13 +0000426 bool needToScanForQualifiers(QualType T);
427 QualType getSuperStructType();
428 QualType getConstantStringStructType();
429 QualType convertFunctionTypeOfBlocks(const FunctionType *FT);
430 bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
431
Fariborz Jahanian8188e5f2010-11-05 18:34:46 +0000432 void convertToUnqualifiedObjCType(QualType &T) {
433 if (T->isObjCQualifiedIdType())
434 T = Context->getObjCIdType();
435 else if (T->isObjCQualifiedClassType())
436 T = Context->getObjCClassType();
437 else if (T->isObjCObjectPointerType() &&
Fariborz Jahanian3a448fb2011-09-10 17:01:56 +0000438 T->getPointeeType()->isObjCQualifiedInterfaceType()) {
439 if (const ObjCObjectPointerType * OBJPT =
440 T->getAsObjCInterfacePointerType()) {
441 const ObjCInterfaceType *IFaceT = OBJPT->getInterfaceType();
442 T = QualType(IFaceT, 0);
443 T = Context->getPointerType(T);
444 }
445 }
Fariborz Jahanian8188e5f2010-11-05 18:34:46 +0000446 }
447
Steve Naroff54055232008-10-27 17:20:55 +0000448 // FIXME: This predicate seems like it would be useful to add to ASTContext.
449 bool isObjCType(QualType T) {
450 if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
451 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000452
Steve Naroff54055232008-10-27 17:20:55 +0000453 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
Mike Stump1eb44332009-09-09 15:08:12 +0000454
Steve Naroff54055232008-10-27 17:20:55 +0000455 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
456 OCT == Context->getCanonicalType(Context->getObjCClassType()))
457 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000458
Ted Kremenek6217b802009-07-29 21:53:49 +0000459 if (const PointerType *PT = OCT->getAs<PointerType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000460 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
Steve Naroffd1b3c2d2009-06-17 22:40:22 +0000461 PT->getPointeeType()->isObjCQualifiedIdType())
Steve Naroff54055232008-10-27 17:20:55 +0000462 return true;
463 }
464 return false;
465 }
466 bool PointerTypeTakesAnyBlockArguments(QualType QT);
Fariborz Jahaniane985d012010-11-03 23:29:24 +0000467 bool PointerTypeTakesAnyObjCQualifiedType(QualType QT);
Ted Kremenek8189cde2009-02-07 01:47:29 +0000468 void GetExtentOfArgList(const char *Name, const char *&LParen,
469 const char *&RParen);
Fariborz Jahanian58457172011-12-05 18:43:13 +0000470
Steve Naroff621edce2009-04-29 16:37:50 +0000471 void QuoteDoublequotes(std::string &From, std::string &To) {
Mike Stump1eb44332009-09-09 15:08:12 +0000472 for (unsigned i = 0; i < From.length(); i++) {
Steve Naroff621edce2009-04-29 16:37:50 +0000473 if (From[i] == '"')
474 To += "\\\"";
475 else
476 To += From[i];
477 }
478 }
John McCalle23cf432010-12-14 08:05:40 +0000479
480 QualType getSimpleFunctionType(QualType result,
481 const QualType *args,
482 unsigned numArgs,
483 bool variadic = false) {
Fariborz Jahanian88914802011-09-09 20:35:22 +0000484 if (result == Context->getObjCInstanceType())
485 result = Context->getObjCIdType();
John McCalle23cf432010-12-14 08:05:40 +0000486 FunctionProtoType::ExtProtoInfo fpi;
487 fpi.Variadic = variadic;
488 return Context->getFunctionType(result, args, numArgs, fpi);
489 }
John McCall9d125032010-01-15 18:39:57 +0000490
Fariborz Jahanian58457172011-12-05 18:43:13 +0000491 // Helper function: create a CStyleCastExpr with trivial type source info.
492 CStyleCastExpr* NoTypeInfoCStyleCastExpr(ASTContext *Ctx, QualType Ty,
493 CastKind Kind, Expr *E) {
494 TypeSourceInfo *TInfo = Ctx->getTrivialTypeSourceInfo(Ty, SourceLocation());
495 return CStyleCastExpr::Create(*Ctx, Ty, VK_RValue, Kind, E, 0, TInfo,
496 SourceLocation(), SourceLocation());
497 }
498 };
Chris Lattner77cd2a02007-10-11 00:43:27 +0000499}
500
Mike Stump1eb44332009-09-09 15:08:12 +0000501void RewriteObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
502 NamedDecl *D) {
John McCallf4c73712011-01-19 06:33:43 +0000503 if (const FunctionProtoType *fproto
Abramo Bagnara723df242010-12-14 22:11:44 +0000504 = dyn_cast<FunctionProtoType>(funcType.IgnoreParens())) {
Mike Stump1eb44332009-09-09 15:08:12 +0000505 for (FunctionProtoType::arg_type_iterator I = fproto->arg_type_begin(),
Steve Naroff54055232008-10-27 17:20:55 +0000506 E = fproto->arg_type_end(); I && (I != E); ++I)
Steve Naroff01f2ffa2008-12-11 21:05:33 +0000507 if (isTopLevelBlockPointerType(*I)) {
Steve Naroff54055232008-10-27 17:20:55 +0000508 // All the args are checked/rewritten. Don't call twice!
509 RewriteBlockPointerDecl(D);
510 break;
511 }
512 }
513}
514
515void RewriteObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000516 const PointerType *PT = funcType->getAs<PointerType>();
Steve Naroff54055232008-10-27 17:20:55 +0000517 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
Douglas Gregor72564e72009-02-26 23:50:07 +0000518 RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
Steve Naroff54055232008-10-27 17:20:55 +0000519}
520
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000521static bool IsHeaderFile(const std::string &Filename) {
522 std::string::size_type DotPos = Filename.rfind('.');
Mike Stump1eb44332009-09-09 15:08:12 +0000523
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000524 if (DotPos == std::string::npos) {
525 // no file extension
Mike Stump1eb44332009-09-09 15:08:12 +0000526 return false;
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000527 }
Mike Stump1eb44332009-09-09 15:08:12 +0000528
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000529 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
530 // C header: .h
531 // C++ header: .hh or .H;
532 return Ext == "h" || Ext == "hh" || Ext == "H";
Mike Stump1eb44332009-09-09 15:08:12 +0000533}
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000534
Chris Lattner5f9e2722011-07-23 10:55:15 +0000535RewriteObjC::RewriteObjC(std::string inFile, raw_ostream* OS,
David Blaikied6471f72011-09-25 23:23:43 +0000536 DiagnosticsEngine &D, const LangOptions &LOpts,
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000537 bool silenceMacroWarn)
538 : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(OS),
539 SilenceRewriteMacroWarning(silenceMacroWarn) {
Steve Naroffa7b402d2008-03-28 22:26:09 +0000540 IsHeader = IsHeaderFile(inFile);
David Blaikied6471f72011-09-25 23:23:43 +0000541 RewriteFailedDiag = Diags.getCustomDiagID(DiagnosticsEngine::Warning,
Steve Naroffa7b402d2008-03-28 22:26:09 +0000542 "rewriting sub-expression within a macro (may not be correct)");
David Blaikied6471f72011-09-25 23:23:43 +0000543 TryFinallyContainsReturnDiag = Diags.getCustomDiagID(
544 DiagnosticsEngine::Warning,
Ted Kremenek8189cde2009-02-07 01:47:29 +0000545 "rewriter doesn't support user-specified control flow semantics "
546 "for @try/@finally (code may not execute properly)");
Steve Naroffa7b402d2008-03-28 22:26:09 +0000547}
548
Eli Friedmanbce831b2009-05-18 22:29:17 +0000549ASTConsumer *clang::CreateObjCRewriter(const std::string& InFile,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000550 raw_ostream* OS,
David Blaikied6471f72011-09-25 23:23:43 +0000551 DiagnosticsEngine &Diags,
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000552 const LangOptions &LOpts,
553 bool SilenceRewriteMacroWarning) {
554 return new RewriteObjC(InFile, OS, Diags, LOpts, SilenceRewriteMacroWarning);
Chris Lattnere365c502007-11-30 22:25:36 +0000555}
Chris Lattner77cd2a02007-10-11 00:43:27 +0000556
Steve Naroffb29b4272008-04-14 22:03:09 +0000557void RewriteObjC::Initialize(ASTContext &context) {
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000558 Context = &context;
559 SM = &Context->getSourceManager();
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +0000560 TUDecl = Context->getTranslationUnitDecl();
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000561 MsgSendFunctionDecl = 0;
562 MsgSendSuperFunctionDecl = 0;
563 MsgSendStretFunctionDecl = 0;
564 MsgSendSuperStretFunctionDecl = 0;
565 MsgSendFpretFunctionDecl = 0;
566 GetClassFunctionDecl = 0;
567 GetMetaClassFunctionDecl = 0;
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +0000568 GetSuperClassFunctionDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000569 SelGetUidFunctionDecl = 0;
570 CFStringFunctionDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000571 ConstantStringClassReference = 0;
572 NSStringRecord = 0;
Steve Naroff54055232008-10-27 17:20:55 +0000573 CurMethodDef = 0;
574 CurFunctionDef = 0;
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +0000575 CurFunctionDeclToDeclareForBlock = 0;
Steve Naroffb619d952008-12-09 12:56:34 +0000576 GlobalVarDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000577 SuperStructDecl = 0;
Steve Naroff621edce2009-04-29 16:37:50 +0000578 ProtocolTypeDecl = 0;
Steve Naroff9630ec52008-03-27 22:59:54 +0000579 ConstantStringDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000580 BcLabelCount = 0;
Steve Naroffc0a123c2008-03-11 17:37:02 +0000581 SuperContructorFunctionDecl = 0;
Steve Naroffd82a9ab2008-03-15 00:55:56 +0000582 NumObjCStringLiterals = 0;
Steve Naroff68272b82008-12-08 20:01:41 +0000583 PropParentMap = 0;
584 CurrentBody = 0;
Steve Naroffb619d952008-12-09 12:56:34 +0000585 DisableReplaceStmt = false;
Fariborz Jahanianf292fcf2010-01-07 22:51:18 +0000586 objc_impl_method = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000587
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000588 // Get the ID and start/end of the main file.
589 MainFileID = SM->getMainFileID();
590 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
591 MainFileStart = MainBuf->getBufferStart();
592 MainFileEnd = MainBuf->getBufferEnd();
Mike Stump1eb44332009-09-09 15:08:12 +0000593
Chris Lattner2c78b872009-04-14 23:22:57 +0000594 Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOptions());
Mike Stump1eb44332009-09-09 15:08:12 +0000595
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000596 // declaring objc_selector outside the parameter list removes a silly
597 // scope related warning...
Steve Naroffba92b2e2008-03-27 22:29:16 +0000598 if (IsHeader)
Steve Naroff62c26322009-02-03 20:39:18 +0000599 Preamble = "#pragma once\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000600 Preamble += "struct objc_selector; struct objc_class;\n";
Steve Naroff46a98a72008-12-23 20:11:22 +0000601 Preamble += "struct __rw_objc_super { struct objc_object *object; ";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000602 Preamble += "struct objc_object *superClass; ";
Francois Pichet62ec1f22011-09-17 17:15:52 +0000603 if (LangOpts.MicrosoftExt) {
Steve Naroffc0a123c2008-03-11 17:37:02 +0000604 // Add a constructor for creating temporary objects.
Ted Kremenek8189cde2009-02-07 01:47:29 +0000605 Preamble += "__rw_objc_super(struct objc_object *o, struct objc_object *s) "
606 ": ";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000607 Preamble += "object(o), superClass(s) {} ";
Steve Naroffc0a123c2008-03-11 17:37:02 +0000608 }
Steve Naroffba92b2e2008-03-27 22:29:16 +0000609 Preamble += "};\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000610 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
611 Preamble += "typedef struct objc_object Protocol;\n";
612 Preamble += "#define _REWRITER_typedef_Protocol\n";
613 Preamble += "#endif\n";
Francois Pichet62ec1f22011-09-17 17:15:52 +0000614 if (LangOpts.MicrosoftExt) {
Steve Naroff4ebd7162008-12-08 17:30:33 +0000615 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
616 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
617 } else
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000618 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000619 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000620 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000621 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000622 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Fariborz Jahanian336c8f72011-10-11 23:02:37 +0000623 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object* objc_msgSend_stret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000624 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Fariborz Jahanian336c8f72011-10-11 23:02:37 +0000625 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object* objc_msgSendSuper_stret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000626 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000627 Preamble += "__OBJC_RW_DLLIMPORT double objc_msgSend_fpret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000628 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000629 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getClass";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000630 Preamble += "(const char *);\n";
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +0000631 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *class_getSuperclass";
632 Preamble += "(struct objc_class *);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000633 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getMetaClass";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000634 Preamble += "(const char *);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000635 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw(struct objc_object *);\n";
636 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_enter(void *);\n";
637 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_exit(void *);\n";
638 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_exception_extract(void *);\n";
639 Preamble += "__OBJC_RW_DLLIMPORT int objc_exception_match";
Steve Naroff580ca782008-05-09 21:17:56 +0000640 Preamble += "(struct objc_class *, struct objc_object *);\n";
Steve Naroff59f05a42008-07-16 18:58:11 +0000641 // @synchronized hooks.
Steve Naroff4ebd7162008-12-08 17:30:33 +0000642 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_enter(struct objc_object *);\n";
643 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_exit(struct objc_object *);\n";
644 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000645 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
646 Preamble += "struct __objcFastEnumerationState {\n\t";
647 Preamble += "unsigned long state;\n\t";
Steve Naroffb10f2732008-04-04 22:58:22 +0000648 Preamble += "void **itemsPtr;\n\t";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000649 Preamble += "unsigned long *mutationsPtr;\n\t";
650 Preamble += "unsigned long extra[5];\n};\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000651 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000652 Preamble += "#define __FASTENUMERATIONSTATE\n";
653 Preamble += "#endif\n";
654 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
655 Preamble += "struct __NSConstantStringImpl {\n";
656 Preamble += " int *isa;\n";
657 Preamble += " int flags;\n";
658 Preamble += " char *str;\n";
659 Preamble += " long length;\n";
660 Preamble += "};\n";
Steve Naroff88bee742008-08-05 20:04:48 +0000661 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
662 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
663 Preamble += "#else\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000664 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
Steve Naroff88bee742008-08-05 20:04:48 +0000665 Preamble += "#endif\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000666 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
667 Preamble += "#endif\n";
Steve Naroff54055232008-10-27 17:20:55 +0000668 // Blocks preamble.
669 Preamble += "#ifndef BLOCK_IMPL\n";
670 Preamble += "#define BLOCK_IMPL\n";
671 Preamble += "struct __block_impl {\n";
672 Preamble += " void *isa;\n";
673 Preamble += " int Flags;\n";
Steve Naroff01aec112009-12-06 21:14:13 +0000674 Preamble += " int Reserved;\n";
Steve Naroff54055232008-10-27 17:20:55 +0000675 Preamble += " void *FuncPtr;\n";
676 Preamble += "};\n";
Steve Naroff5bc60d02008-12-16 15:50:30 +0000677 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
Steve Naroffc9c1e9c2009-12-06 01:52:22 +0000678 Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000679 Preamble += "extern \"C\" __declspec(dllexport) "
680 "void _Block_object_assign(void *, const void *, const int);\n";
Steve Naroffa851e602009-12-06 01:33:56 +0000681 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
682 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
683 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
684 Preamble += "#else\n";
Steve Naroffcd826372010-01-05 18:09:31 +0000685 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
686 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
Steve Naroffa851e602009-12-06 01:33:56 +0000687 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
688 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
689 Preamble += "#endif\n";
Steve Naroff54055232008-10-27 17:20:55 +0000690 Preamble += "#endif\n";
Francois Pichet62ec1f22011-09-17 17:15:52 +0000691 if (LangOpts.MicrosoftExt) {
Steve Naroff4ebd7162008-12-08 17:30:33 +0000692 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
693 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
Chris Lattner553e5832010-04-13 17:33:56 +0000694 Preamble += "#ifndef KEEP_ATTRIBUTES\n"; // We use this for clang tests.
Steve Naroffa48396e2008-10-27 18:50:14 +0000695 Preamble += "#define __attribute__(X)\n";
Chris Lattner553e5832010-04-13 17:33:56 +0000696 Preamble += "#endif\n";
Fariborz Jahanian34204192010-01-15 22:29:39 +0000697 Preamble += "#define __weak\n";
Steve Naroffa48396e2008-10-27 18:50:14 +0000698 }
Fariborz Jahanian2086d542010-01-05 19:21:35 +0000699 else {
Fariborz Jahanian52b08f22009-12-23 02:07:37 +0000700 Preamble += "#define __block\n";
Fariborz Jahanian2086d542010-01-05 19:21:35 +0000701 Preamble += "#define __weak\n";
702 }
Fariborz Jahaniandf496522010-03-02 01:19:04 +0000703 // NOTE! Windows uses LLP64 for 64bit mode. So, cast pointer to long long
704 // as this avoids warning in any 64bit/32bit compilation model.
705 Preamble += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long long) &((TYPE *)0)->MEMBER)\n";
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000706}
707
708
Chris Lattnerf04da132007-10-24 17:06:59 +0000709//===----------------------------------------------------------------------===//
710// Top Level Driver Code
711//===----------------------------------------------------------------------===//
712
Chris Lattner682bf922009-03-29 16:50:03 +0000713void RewriteObjC::HandleTopLevelSingleDecl(Decl *D) {
Ted Kremeneke50187a2010-02-05 21:28:51 +0000714 if (Diags.hasErrorOccurred())
715 return;
716
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000717 // Two cases: either the decl could be in the main file, or it could be in a
718 // #included file. If the former, rewrite it now. If the later, check to see
719 // if we rewrote the #include/#import.
720 SourceLocation Loc = D->getLocation();
Chandler Carruth40278532011-07-25 16:49:02 +0000721 Loc = SM->getExpansionLoc(Loc);
Mike Stump1eb44332009-09-09 15:08:12 +0000722
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000723 // If this is for a builtin, ignore it.
724 if (Loc.isInvalid()) return;
725
Steve Naroffebf2b562007-10-23 23:50:29 +0000726 // Look for built-in declarations that we need to refer during the rewrite.
727 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff09b266e2007-10-30 23:14:51 +0000728 RewriteFunctionDecl(FD);
Steve Naroff248a7532008-04-15 22:42:06 +0000729 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000730 // declared in <Foundation/NSString.h>
Daniel Dunbar4087f272010-08-17 22:39:59 +0000731 if (FVD->getName() == "_NSConstantStringClassReference") {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000732 ConstantStringClassReference = FVD;
733 return;
734 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000735 } else if (ObjCInterfaceDecl *MD = dyn_cast<ObjCInterfaceDecl>(D)) {
Steve Naroffbef11852007-10-26 20:53:56 +0000736 RewriteInterfaceDecl(MD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000737 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Steve Naroff423cb562007-10-30 13:30:57 +0000738 RewriteCategoryDecl(CD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000739 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
Steve Naroff752d6ef2007-10-30 16:42:30 +0000740 RewriteProtocolDecl(PD);
Mike Stump1eb44332009-09-09 15:08:12 +0000741 } else if (ObjCForwardProtocolDecl *FP =
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000742 dyn_cast<ObjCForwardProtocolDecl>(D)){
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000743 RewriteForwardProtocolDecl(FP);
Douglas Gregord0434102009-01-09 00:49:46 +0000744 } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
745 // Recurse into linkage specifications
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000746 for (DeclContext::decl_iterator DI = LSD->decls_begin(),
747 DIEnd = LSD->decls_end();
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000748 DI != DIEnd; ) {
749 if (isa<ObjCClassDecl>((*DI))) {
750 SmallVector<Decl *, 8> DG;
751 Decl *D = (*DI);
752 SourceLocation Loc = D->getLocation();
753 while (DI != DIEnd &&
754 isa<ObjCClassDecl>(D) && D->getLocation() == Loc) {
755 DG.push_back(D);
756 ++DI;
757 D = (*DI);
758 }
759 RewriteForwardClassDecl(DG);
760 continue;
761 }
Chris Lattner682bf922009-03-29 16:50:03 +0000762 HandleTopLevelSingleDecl(*DI);
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000763 ++DI;
764 }
Steve Naroffebf2b562007-10-23 23:50:29 +0000765 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000766 // If we have a decl in the main file, see if we should rewrite it.
Ted Kremenekcf7e9582008-04-14 21:24:13 +0000767 if (SM->isFromMainFile(Loc))
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000768 return HandleDeclInMainFile(D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000769}
770
Chris Lattnerf04da132007-10-24 17:06:59 +0000771//===----------------------------------------------------------------------===//
772// Syntactic (non-AST) Rewriting Code
773//===----------------------------------------------------------------------===//
774
Steve Naroffb29b4272008-04-14 22:03:09 +0000775void RewriteObjC::RewriteInclude() {
Chris Lattner2b2453a2009-01-17 06:22:33 +0000776 SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
Chris Lattner5f9e2722011-07-23 10:55:15 +0000777 StringRef MainBuf = SM->getBufferData(MainFileID);
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +0000778 const char *MainBufStart = MainBuf.begin();
779 const char *MainBufEnd = MainBuf.end();
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000780 size_t ImportLen = strlen("import");
Mike Stump1eb44332009-09-09 15:08:12 +0000781
Fariborz Jahanianaf57b462008-01-19 01:03:17 +0000782 // Loop over the whole file, looking for includes.
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000783 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
784 if (*BufPtr == '#') {
785 if (++BufPtr == MainBufEnd)
786 return;
787 while (*BufPtr == ' ' || *BufPtr == '\t')
788 if (++BufPtr == MainBufEnd)
789 return;
790 if (!strncmp(BufPtr, "import", ImportLen)) {
791 // replace import with include
Mike Stump1eb44332009-09-09 15:08:12 +0000792 SourceLocation ImportLoc =
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +0000793 LocStart.getLocWithOffset(BufPtr-MainBufStart);
Benjamin Kramerd999b372010-02-14 14:14:16 +0000794 ReplaceText(ImportLoc, ImportLen, "include");
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000795 BufPtr += ImportLen;
796 }
797 }
798 }
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000799}
800
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +0000801static std::string getIvarAccessString(ObjCIvarDecl *OID) {
802 const ObjCInterfaceDecl *ClassDecl = OID->getContainingInterface();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000803 std::string S;
804 S = "((struct ";
805 S += ClassDecl->getIdentifier()->getName();
806 S += "_IMPL *)self)->";
Daniel Dunbar5ffe14c2009-10-18 20:26:27 +0000807 S += OID->getName();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000808 return S;
809}
810
Steve Naroffa0876e82008-12-02 17:36:43 +0000811void RewriteObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
812 ObjCImplementationDecl *IMD,
813 ObjCCategoryImplDecl *CID) {
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000814 static bool objcGetPropertyDefined = false;
815 static bool objcSetPropertyDefined = false;
Steve Naroffd40910b2008-12-01 20:33:01 +0000816 SourceLocation startLoc = PID->getLocStart();
Benjamin Kramerd999b372010-02-14 14:14:16 +0000817 InsertText(startLoc, "// ");
Steve Naroffeb0646c2008-12-02 15:48:25 +0000818 const char *startBuf = SM->getCharacterData(startLoc);
819 assert((*startBuf == '@') && "bogus @synthesize location");
820 const char *semiBuf = strchr(startBuf, ';');
821 assert((*semiBuf == ';') && "@synthesize: can't find ';'");
Ted Kremenek8189cde2009-02-07 01:47:29 +0000822 SourceLocation onePastSemiLoc =
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +0000823 startLoc.getLocWithOffset(semiBuf-startBuf+1);
Steve Naroffeb0646c2008-12-02 15:48:25 +0000824
825 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
826 return; // FIXME: is this correct?
Mike Stump1eb44332009-09-09 15:08:12 +0000827
Steve Naroffeb0646c2008-12-02 15:48:25 +0000828 // Generate the 'getter' function.
Steve Naroffeb0646c2008-12-02 15:48:25 +0000829 ObjCPropertyDecl *PD = PID->getPropertyDecl();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000830 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000831
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000832 if (!OID)
833 return;
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000834 unsigned Attributes = PD->getPropertyAttributes();
Fariborz Jahanianec3683b2010-10-19 23:47:54 +0000835 if (!PD->getGetterMethodDecl()->isDefined()) {
836 bool GenGetProperty = !(Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic) &&
837 (Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
838 ObjCPropertyDecl::OBJC_PR_copy));
839 std::string Getr;
840 if (GenGetProperty && !objcGetPropertyDefined) {
841 objcGetPropertyDefined = true;
842 // FIXME. Is this attribute correct in all cases?
843 Getr = "\nextern \"C\" __declspec(dllimport) "
844 "id objc_getProperty(id, SEL, long, bool);\n";
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000845 }
Fariborz Jahanianec3683b2010-10-19 23:47:54 +0000846 RewriteObjCMethodDecl(OID->getContainingInterface(),
847 PD->getGetterMethodDecl(), Getr);
848 Getr += "{ ";
849 // Synthesize an explicit cast to gain access to the ivar.
850 // See objc-act.c:objc_synthesize_new_getter() for details.
851 if (GenGetProperty) {
852 // return objc_getProperty(self, _cmd, offsetof(ClassDecl, OID), 1)
853 Getr += "typedef ";
854 const FunctionType *FPRetType = 0;
855 RewriteTypeIntoString(PD->getGetterMethodDecl()->getResultType(), Getr,
856 FPRetType);
857 Getr += " _TYPE";
858 if (FPRetType) {
859 Getr += ")"; // close the precedence "scope" for "*".
860
861 // Now, emit the argument types (if any).
862 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)){
863 Getr += "(";
864 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
865 if (i) Getr += ", ";
866 std::string ParamStr = FT->getArgType(i).getAsString(
Douglas Gregor30c42402011-09-27 22:38:19 +0000867 Context->getPrintingPolicy());
Fariborz Jahanianec3683b2010-10-19 23:47:54 +0000868 Getr += ParamStr;
869 }
870 if (FT->isVariadic()) {
871 if (FT->getNumArgs()) Getr += ", ";
872 Getr += "...";
873 }
874 Getr += ")";
875 } else
876 Getr += "()";
877 }
878 Getr += ";\n";
879 Getr += "return (_TYPE)";
880 Getr += "objc_getProperty(self, _cmd, ";
Fariborz Jahanian58457172011-12-05 18:43:13 +0000881 RewriteIvarOffsetComputation(OID, Getr);
Fariborz Jahanianec3683b2010-10-19 23:47:54 +0000882 Getr += ", 1)";
883 }
884 else
885 Getr += "return " + getIvarAccessString(OID);
886 Getr += "; }";
887 InsertText(onePastSemiLoc, Getr);
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000888 }
Fariborz Jahanianec3683b2010-10-19 23:47:54 +0000889
890 if (PD->isReadOnly() || PD->getSetterMethodDecl()->isDefined())
Steve Naroffeb0646c2008-12-02 15:48:25 +0000891 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000892
Steve Naroffeb0646c2008-12-02 15:48:25 +0000893 // Generate the 'setter' function.
894 std::string Setr;
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000895 bool GenSetProperty = Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
896 ObjCPropertyDecl::OBJC_PR_copy);
897 if (GenSetProperty && !objcSetPropertyDefined) {
898 objcSetPropertyDefined = true;
899 // FIXME. Is this attribute correct in all cases?
900 Setr = "\nextern \"C\" __declspec(dllimport) "
901 "void objc_setProperty (id, SEL, long, id, bool, bool);\n";
902 }
903
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +0000904 RewriteObjCMethodDecl(OID->getContainingInterface(),
905 PD->getSetterMethodDecl(), Setr);
Steve Naroffeb0646c2008-12-02 15:48:25 +0000906 Setr += "{ ";
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000907 // Synthesize an explicit cast to initialize the ivar.
Steve Naroff15f081d2008-12-03 00:56:33 +0000908 // See objc-act.c:objc_synthesize_new_setter() for details.
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000909 if (GenSetProperty) {
910 Setr += "objc_setProperty (self, _cmd, ";
Fariborz Jahanian58457172011-12-05 18:43:13 +0000911 RewriteIvarOffsetComputation(OID, Setr);
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000912 Setr += ", (id)";
Daniel Dunbar4087f272010-08-17 22:39:59 +0000913 Setr += PD->getName();
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000914 Setr += ", ";
915 if (Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic)
916 Setr += "0, ";
917 else
918 Setr += "1, ";
919 if (Attributes & ObjCPropertyDecl::OBJC_PR_copy)
920 Setr += "1)";
921 else
922 Setr += "0)";
923 }
924 else {
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +0000925 Setr += getIvarAccessString(OID) + " = ";
Daniel Dunbar4087f272010-08-17 22:39:59 +0000926 Setr += PD->getName();
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000927 }
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000928 Setr += "; }";
Benjamin Kramerd999b372010-02-14 14:14:16 +0000929 InsertText(onePastSemiLoc, Setr);
Steve Naroffd40910b2008-12-01 20:33:01 +0000930}
Chris Lattner8a12c272007-10-11 18:38:32 +0000931
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000932static void RewriteOneForwardClassDecl(ObjCInterfaceDecl *ForwardDecl,
933 std::string &typedefString) {
934 typedefString += "#ifndef _REWRITER_typedef_";
935 typedefString += ForwardDecl->getNameAsString();
936 typedefString += "\n";
937 typedefString += "#define _REWRITER_typedef_";
938 typedefString += ForwardDecl->getNameAsString();
939 typedefString += "\n";
940 typedefString += "typedef struct objc_object ";
941 typedefString += ForwardDecl->getNameAsString();
942 typedefString += ";\n#endif\n";
943}
944
945void RewriteObjC::RewriteForwardClassEpilogue(ObjCClassDecl *ClassDecl,
946 const std::string &typedefString) {
947 SourceLocation startLoc = ClassDecl->getLocation();
948 const char *startBuf = SM->getCharacterData(startLoc);
949 const char *semiPtr = strchr(startBuf, ';');
950 // Replace the @class with typedefs corresponding to the classes.
951 ReplaceText(startLoc, semiPtr-startBuf+1, typedefString);
952}
953
Fariborz Jahanian95ed7782011-08-27 20:50:59 +0000954void RewriteObjC::RewriteForwardClassDecl(DeclGroupRef D) {
Chris Lattnerf04da132007-10-24 17:06:59 +0000955 std::string typedefString;
Fariborz Jahanian95ed7782011-08-27 20:50:59 +0000956 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
957 ObjCClassDecl *ClassDecl = cast<ObjCClassDecl>(*I);
958 ObjCInterfaceDecl *ForwardDecl = ClassDecl->getForwardInterfaceDecl();
959 if (I == D.begin()) {
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000960 // Translate to typedef's that forward reference structs with the same name
961 // as the class. As a convenience, we include the original declaration
962 // as a comment.
Fariborz Jahanian95ed7782011-08-27 20:50:59 +0000963 typedefString += "// @class ";
964 typedefString += ForwardDecl->getNameAsString();
Fariborz Jahanian91fbd122010-01-11 22:48:40 +0000965 typedefString += ";\n";
Fariborz Jahanian95ed7782011-08-27 20:50:59 +0000966 }
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000967 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
Steve Naroff934f2762007-10-24 22:48:43 +0000968 }
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000969 DeclGroupRef::iterator I = D.begin();
970 RewriteForwardClassEpilogue(cast<ObjCClassDecl>(*I), typedefString);
971}
Mike Stump1eb44332009-09-09 15:08:12 +0000972
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000973void RewriteObjC::RewriteForwardClassDecl(
974 const llvm::SmallVector<Decl*, 8> &D) {
975 std::string typedefString;
976 for (unsigned i = 0; i < D.size(); i++) {
977 ObjCClassDecl *ClassDecl = cast<ObjCClassDecl>(D[i]);
978 ObjCInterfaceDecl *ForwardDecl = ClassDecl->getForwardInterfaceDecl();
979 if (i == 0) {
980 typedefString += "// @class ";
981 typedefString += ForwardDecl->getNameAsString();
982 typedefString += ";\n";
983 }
984 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
985 }
986 RewriteForwardClassEpilogue(cast<ObjCClassDecl>(D[0]), typedefString);
Chris Lattnerf04da132007-10-24 17:06:59 +0000987}
988
Steve Naroffb29b4272008-04-14 22:03:09 +0000989void RewriteObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
Fariborz Jahaniand0502402010-01-21 17:36:00 +0000990 // When method is a synthesized one, such as a getter/setter there is
991 // nothing to rewrite.
Fariborz Jahanian88914802011-09-09 20:35:22 +0000992 if (Method->isImplicit())
Fariborz Jahaniand0502402010-01-21 17:36:00 +0000993 return;
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000994 SourceLocation LocStart = Method->getLocStart();
995 SourceLocation LocEnd = Method->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +0000996
Chandler Carruth64211622011-07-25 21:09:52 +0000997 if (SM->getExpansionLineNumber(LocEnd) >
998 SM->getExpansionLineNumber(LocStart)) {
Benjamin Kramerd999b372010-02-14 14:14:16 +0000999 InsertText(LocStart, "#if 0\n");
1000 ReplaceText(LocEnd, 1, ";\n#endif\n");
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001001 } else {
Benjamin Kramerd999b372010-02-14 14:14:16 +00001002 InsertText(LocStart, "// ");
Steve Naroff423cb562007-10-30 13:30:57 +00001003 }
1004}
1005
Mike Stump1eb44332009-09-09 15:08:12 +00001006void RewriteObjC::RewriteProperty(ObjCPropertyDecl *prop) {
Fariborz Jahaniand0502402010-01-21 17:36:00 +00001007 SourceLocation Loc = prop->getAtLoc();
Mike Stump1eb44332009-09-09 15:08:12 +00001008
Benjamin Kramerd999b372010-02-14 14:14:16 +00001009 ReplaceText(Loc, 0, "// ");
Steve Naroff6327e0d2009-01-11 01:06:09 +00001010 // FIXME: handle properties that are declared across multiple lines.
Fariborz Jahanian957cf652007-11-07 00:09:37 +00001011}
1012
Steve Naroffb29b4272008-04-14 22:03:09 +00001013void RewriteObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Steve Naroff423cb562007-10-30 13:30:57 +00001014 SourceLocation LocStart = CatDecl->getLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +00001015
Steve Naroff423cb562007-10-30 13:30:57 +00001016 // FIXME: handle category headers that are declared across multiple lines.
Benjamin Kramerd999b372010-02-14 14:14:16 +00001017 ReplaceText(LocStart, 0, "// ");
Mike Stump1eb44332009-09-09 15:08:12 +00001018
Fariborz Jahanian13751e32010-02-10 01:15:09 +00001019 for (ObjCCategoryDecl::prop_iterator I = CatDecl->prop_begin(),
1020 E = CatDecl->prop_end(); I != E; ++I)
1021 RewriteProperty(*I);
1022
Mike Stump1eb44332009-09-09 15:08:12 +00001023 for (ObjCCategoryDecl::instmeth_iterator
1024 I = CatDecl->instmeth_begin(), E = CatDecl->instmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00001025 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001026 RewriteMethodDeclaration(*I);
Mike Stump1eb44332009-09-09 15:08:12 +00001027 for (ObjCCategoryDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001028 I = CatDecl->classmeth_begin(), E = CatDecl->classmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00001029 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001030 RewriteMethodDeclaration(*I);
1031
Steve Naroff423cb562007-10-30 13:30:57 +00001032 // Lastly, comment out the @end.
Fariborz Jahanian73d1eb02010-05-24 17:22:38 +00001033 ReplaceText(CatDecl->getAtEndRange().getBegin(),
1034 strlen("@end"), "/* @end */");
Steve Naroff423cb562007-10-30 13:30:57 +00001035}
1036
Steve Naroffb29b4272008-04-14 22:03:09 +00001037void RewriteObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Steve Naroff752d6ef2007-10-30 16:42:30 +00001038 SourceLocation LocStart = PDecl->getLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +00001039
Steve Naroff752d6ef2007-10-30 16:42:30 +00001040 // FIXME: handle protocol headers that are declared across multiple lines.
Benjamin Kramerd999b372010-02-14 14:14:16 +00001041 ReplaceText(LocStart, 0, "// ");
Mike Stump1eb44332009-09-09 15:08:12 +00001042
1043 for (ObjCProtocolDecl::instmeth_iterator
1044 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00001045 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001046 RewriteMethodDeclaration(*I);
Douglas Gregor6ab35242009-04-09 21:40:53 +00001047 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001048 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00001049 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001050 RewriteMethodDeclaration(*I);
1051
Fariborz Jahanian07acdf42010-09-24 18:36:58 +00001052 for (ObjCInterfaceDecl::prop_iterator I = PDecl->prop_begin(),
1053 E = PDecl->prop_end(); I != E; ++I)
1054 RewriteProperty(*I);
1055
Steve Naroff752d6ef2007-10-30 16:42:30 +00001056 // Lastly, comment out the @end.
Ted Kremenek782f2f52010-01-07 01:20:12 +00001057 SourceLocation LocEnd = PDecl->getAtEndRange().getBegin();
Fariborz Jahanian73d1eb02010-05-24 17:22:38 +00001058 ReplaceText(LocEnd, strlen("@end"), "/* @end */");
Steve Naroff8cc764c2007-11-14 15:03:57 +00001059
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +00001060 // Must comment out @optional/@required
1061 const char *startBuf = SM->getCharacterData(LocStart);
1062 const char *endBuf = SM->getCharacterData(LocEnd);
1063 for (const char *p = startBuf; p < endBuf; p++) {
1064 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001065 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001066 ReplaceText(OptionalLoc, strlen("@optional"), "/* @optional */");
Mike Stump1eb44332009-09-09 15:08:12 +00001067
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +00001068 }
1069 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001070 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001071 ReplaceText(OptionalLoc, strlen("@required"), "/* @required */");
Mike Stump1eb44332009-09-09 15:08:12 +00001072
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +00001073 }
1074 }
Steve Naroff752d6ef2007-10-30 16:42:30 +00001075}
1076
Steve Naroffb29b4272008-04-14 22:03:09 +00001077void RewriteObjC::RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *PDecl) {
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +00001078 SourceLocation LocStart = PDecl->getLocation();
Steve Naroffb7fa9922007-11-14 03:37:28 +00001079 if (LocStart.isInvalid())
David Blaikieb219cfc2011-09-23 05:06:16 +00001080 llvm_unreachable("Invalid SourceLocation");
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +00001081 // FIXME: handle forward protocol that are declared across multiple lines.
Benjamin Kramerd999b372010-02-14 14:14:16 +00001082 ReplaceText(LocStart, 0, "// ");
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +00001083}
1084
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001085void RewriteObjC::RewriteTypeIntoString(QualType T, std::string &ResultStr,
1086 const FunctionType *&FPRetType) {
1087 if (T->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001088 ResultStr += "id";
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001089 else if (T->isFunctionPointerType() ||
1090 T->isBlockPointerType()) {
Steve Naroff76e429d2008-07-16 14:40:40 +00001091 // needs special handling, since pointer-to-functions have special
1092 // syntax (where a decaration models use).
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001093 QualType retType = T;
Steve Narofff4312dc2008-12-11 19:29:16 +00001094 QualType PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00001095 if (const PointerType* PT = retType->getAs<PointerType>())
Steve Narofff4312dc2008-12-11 19:29:16 +00001096 PointeeTy = PT->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001097 else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
Steve Narofff4312dc2008-12-11 19:29:16 +00001098 PointeeTy = BPT->getPointeeType();
John McCall183700f2009-09-21 23:43:11 +00001099 if ((FPRetType = PointeeTy->getAs<FunctionType>())) {
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00001100 ResultStr += FPRetType->getResultType().getAsString(
Douglas Gregor30c42402011-09-27 22:38:19 +00001101 Context->getPrintingPolicy());
Steve Narofff4312dc2008-12-11 19:29:16 +00001102 ResultStr += "(*";
Steve Naroff76e429d2008-07-16 14:40:40 +00001103 }
1104 } else
Douglas Gregor30c42402011-09-27 22:38:19 +00001105 ResultStr += T.getAsString(Context->getPrintingPolicy());
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001106}
1107
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001108void RewriteObjC::RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
1109 ObjCMethodDecl *OMD,
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001110 std::string &ResultStr) {
1111 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
1112 const FunctionType *FPRetType = 0;
1113 ResultStr += "\nstatic ";
1114 RewriteTypeIntoString(OMD->getResultType(), ResultStr, FPRetType);
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +00001115 ResultStr += " ";
Mike Stump1eb44332009-09-09 15:08:12 +00001116
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001117 // Unique method name
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001118 std::string NameStr;
Mike Stump1eb44332009-09-09 15:08:12 +00001119
Douglas Gregorf8d49f62009-01-09 17:18:27 +00001120 if (OMD->isInstanceMethod())
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001121 NameStr += "_I_";
1122 else
1123 NameStr += "_C_";
Mike Stump1eb44332009-09-09 15:08:12 +00001124
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001125 NameStr += IDecl->getNameAsString();
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001126 NameStr += "_";
Mike Stump1eb44332009-09-09 15:08:12 +00001127
1128 if (ObjCCategoryImplDecl *CID =
Steve Naroff3e0a5402009-01-08 19:41:02 +00001129 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001130 NameStr += CID->getNameAsString();
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001131 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001132 }
Mike Stump1eb44332009-09-09 15:08:12 +00001133 // Append selector names, replacing ':' with '_'
Chris Lattner077bf5e2008-11-24 03:33:13 +00001134 {
1135 std::string selString = OMD->getSelector().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001136 int len = selString.size();
1137 for (int i = 0; i < len; i++)
1138 if (selString[i] == ':')
1139 selString[i] = '_';
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001140 NameStr += selString;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001141 }
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001142 // Remember this name for metadata emission
1143 MethodInternalNames[OMD] = NameStr;
1144 ResultStr += NameStr;
Mike Stump1eb44332009-09-09 15:08:12 +00001145
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001146 // Rewrite arguments
1147 ResultStr += "(";
Mike Stump1eb44332009-09-09 15:08:12 +00001148
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001149 // invisible arguments
Douglas Gregorf8d49f62009-01-09 17:18:27 +00001150 if (OMD->isInstanceMethod()) {
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001151 QualType selfTy = Context->getObjCInterfaceType(IDecl);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001152 selfTy = Context->getPointerType(selfTy);
Francois Pichet62ec1f22011-09-17 17:15:52 +00001153 if (!LangOpts.MicrosoftExt) {
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001154 if (ObjCSynthesizedStructs.count(const_cast<ObjCInterfaceDecl*>(IDecl)))
Steve Naroff05b8c782008-03-12 00:25:36 +00001155 ResultStr += "struct ";
1156 }
1157 // When rewriting for Microsoft, explicitly omit the structure name.
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001158 ResultStr += IDecl->getNameAsString();
Steve Naroff61ed9ca2008-03-10 23:16:54 +00001159 ResultStr += " *";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001160 }
1161 else
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00001162 ResultStr += Context->getObjCClassType().getAsString(
Douglas Gregor30c42402011-09-27 22:38:19 +00001163 Context->getPrintingPolicy());
Mike Stump1eb44332009-09-09 15:08:12 +00001164
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001165 ResultStr += " self, ";
Douglas Gregor30c42402011-09-27 22:38:19 +00001166 ResultStr += Context->getObjCSelType().getAsString(Context->getPrintingPolicy());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001167 ResultStr += " _cmd";
Mike Stump1eb44332009-09-09 15:08:12 +00001168
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001169 // Method arguments.
Chris Lattner89951a82009-02-20 18:43:26 +00001170 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
1171 E = OMD->param_end(); PI != E; ++PI) {
1172 ParmVarDecl *PDecl = *PI;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001173 ResultStr += ", ";
Steve Naroff543409e2008-04-18 21:13:19 +00001174 if (PDecl->getType()->isObjCQualifiedIdType()) {
1175 ResultStr += "id ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001176 ResultStr += PDecl->getNameAsString();
Steve Naroff543409e2008-04-18 21:13:19 +00001177 } else {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001178 std::string Name = PDecl->getNameAsString();
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00001179 QualType QT = PDecl->getType();
1180 // Make sure we convert "t (^)(...)" to "t (*)(...)".
1181 if (convertBlockPointerToFunctionPointer(QT))
Douglas Gregor30c42402011-09-27 22:38:19 +00001182 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00001183 else
Douglas Gregor30c42402011-09-27 22:38:19 +00001184 PDecl->getType().getAsStringInternal(Name, Context->getPrintingPolicy());
Steve Naroff543409e2008-04-18 21:13:19 +00001185 ResultStr += Name;
1186 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001187 }
Fariborz Jahanian7c39ff72008-01-21 20:14:23 +00001188 if (OMD->isVariadic())
1189 ResultStr += ", ...";
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +00001190 ResultStr += ") ";
Mike Stump1eb44332009-09-09 15:08:12 +00001191
Steve Naroff76e429d2008-07-16 14:40:40 +00001192 if (FPRetType) {
1193 ResultStr += ")"; // close the precedence "scope" for "*".
Mike Stump1eb44332009-09-09 15:08:12 +00001194
Steve Naroff76e429d2008-07-16 14:40:40 +00001195 // Now, emit the argument types (if any).
Douglas Gregor72564e72009-02-26 23:50:07 +00001196 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
Steve Naroff76e429d2008-07-16 14:40:40 +00001197 ResultStr += "(";
1198 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
1199 if (i) ResultStr += ", ";
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00001200 std::string ParamStr = FT->getArgType(i).getAsString(
Douglas Gregor30c42402011-09-27 22:38:19 +00001201 Context->getPrintingPolicy());
Steve Naroff76e429d2008-07-16 14:40:40 +00001202 ResultStr += ParamStr;
1203 }
1204 if (FT->isVariadic()) {
1205 if (FT->getNumArgs()) ResultStr += ", ";
1206 ResultStr += "...";
1207 }
1208 ResultStr += ")";
1209 } else {
1210 ResultStr += "()";
1211 }
1212 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001213}
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001214void RewriteObjC::RewriteImplementationDecl(Decl *OID) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001215 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
1216 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Mike Stump1eb44332009-09-09 15:08:12 +00001217
Fariborz Jahaniana1352162010-02-15 21:11:41 +00001218 InsertText(IMD ? IMD->getLocStart() : CID->getLocStart(), "// ");
Mike Stump1eb44332009-09-09 15:08:12 +00001219
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001220 for (ObjCCategoryImplDecl::instmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001221 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
1222 E = IMD ? IMD->instmeth_end() : CID->instmeth_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001223 I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001224 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001225 ObjCMethodDecl *OMD = *I;
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001226 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001227 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001228 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Sebastian Redld3a413d2009-04-26 20:35:05 +00001229
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001230 const char *startBuf = SM->getCharacterData(LocStart);
1231 const char *endBuf = SM->getCharacterData(LocEnd);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001232 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001233 }
Mike Stump1eb44332009-09-09 15:08:12 +00001234
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001235 for (ObjCCategoryImplDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001236 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
1237 E = IMD ? IMD->classmeth_end() : CID->classmeth_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001238 I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001239 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001240 ObjCMethodDecl *OMD = *I;
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001241 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001242 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001243 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +00001244
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001245 const char *startBuf = SM->getCharacterData(LocStart);
1246 const char *endBuf = SM->getCharacterData(LocEnd);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001247 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001248 }
Steve Naroffd40910b2008-12-01 20:33:01 +00001249 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001250 I = IMD ? IMD->propimpl_begin() : CID->propimpl_begin(),
Mike Stump1eb44332009-09-09 15:08:12 +00001251 E = IMD ? IMD->propimpl_end() : CID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001252 I != E; ++I) {
Steve Naroffa0876e82008-12-02 17:36:43 +00001253 RewritePropertyImplDecl(*I, IMD, CID);
Steve Naroffd40910b2008-12-01 20:33:01 +00001254 }
1255
Benjamin Kramerd999b372010-02-14 14:14:16 +00001256 InsertText(IMD ? IMD->getLocEnd() : CID->getLocEnd(), "// ");
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001257}
1258
Steve Naroffb29b4272008-04-14 22:03:09 +00001259void RewriteObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Narofff908a872007-10-30 02:23:23 +00001260 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001261 if (!ObjCForwardDecls.count(ClassDecl)) {
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001262 // we haven't seen a forward decl - generate a typedef.
Steve Naroff5086a8d2007-11-14 23:02:56 +00001263 ResultStr = "#ifndef _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001264 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001265 ResultStr += "\n";
1266 ResultStr += "#define _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001267 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001268 ResultStr += "\n";
Steve Naroff61ed9ca2008-03-10 23:16:54 +00001269 ResultStr += "typedef struct objc_object ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001270 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001271 ResultStr += ";\n#endif\n";
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001272 // Mark this typedef as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001273 ObjCForwardDecls.insert(ClassDecl);
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001274 }
Fariborz Jahanian58457172011-12-05 18:43:13 +00001275 RewriteObjCInternalStruct(ClassDecl, ResultStr);
Mike Stump1eb44332009-09-09 15:08:12 +00001276
1277 for (ObjCInterfaceDecl::prop_iterator I = ClassDecl->prop_begin(),
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001278 E = ClassDecl->prop_end(); I != E; ++I)
Steve Naroff6327e0d2009-01-11 01:06:09 +00001279 RewriteProperty(*I);
Mike Stump1eb44332009-09-09 15:08:12 +00001280 for (ObjCInterfaceDecl::instmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001281 I = ClassDecl->instmeth_begin(), E = ClassDecl->instmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00001282 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001283 RewriteMethodDeclaration(*I);
Mike Stump1eb44332009-09-09 15:08:12 +00001284 for (ObjCInterfaceDecl::classmeth_iterator
1285 I = ClassDecl->classmeth_begin(), E = ClassDecl->classmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00001286 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001287 RewriteMethodDeclaration(*I);
1288
Steve Naroff2feac5e2007-10-30 03:43:13 +00001289 // Lastly, comment out the @end.
Fariborz Jahanian73d1eb02010-05-24 17:22:38 +00001290 ReplaceText(ClassDecl->getAtEndRange().getBegin(), strlen("@end"),
1291 "/* @end */");
Steve Naroffbef11852007-10-26 20:53:56 +00001292}
1293
John McCall4b9c2d22011-11-06 09:01:30 +00001294Stmt *RewriteObjC::RewritePropertyOrImplicitSetter(PseudoObjectExpr *PseudoOp) {
1295 SourceRange OldRange = PseudoOp->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00001296
John McCall4b9c2d22011-11-06 09:01:30 +00001297 // We just magically know some things about the structure of this
1298 // expression.
1299 ObjCMessageExpr *OldMsg =
1300 cast<ObjCMessageExpr>(PseudoOp->getSemanticExpr(
1301 PseudoOp->getNumSemanticExprs() - 1));
Mike Stump1eb44332009-09-09 15:08:12 +00001302
John McCall4b9c2d22011-11-06 09:01:30 +00001303 // Because the rewriter doesn't allow us to rewrite rewritten code,
1304 // we need to suppress rewriting the sub-statements.
1305 Expr *Base, *RHS;
1306 {
1307 DisableReplaceStmtScope S(*this);
1308
1309 // Rebuild the base expression if we have one.
1310 Base = 0;
1311 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1312 Base = OldMsg->getInstanceReceiver();
1313 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1314 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1315 }
1316
1317 // Rebuild the RHS.
1318 RHS = cast<BinaryOperator>(PseudoOp->getSyntacticForm())->getRHS();
1319 RHS = cast<OpaqueValueExpr>(RHS)->getSourceExpr();
1320 RHS = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(RHS));
1321 }
1322
1323 // TODO: avoid this copy.
1324 SmallVector<SourceLocation, 1> SelLocs;
1325 OldMsg->getSelectorLocs(SelLocs);
1326
1327 ObjCMessageExpr *NewMsg;
1328 switch (OldMsg->getReceiverKind()) {
1329 case ObjCMessageExpr::Class:
1330 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1331 OldMsg->getValueKind(),
1332 OldMsg->getLeftLoc(),
1333 OldMsg->getClassReceiverTypeInfo(),
1334 OldMsg->getSelector(),
1335 SelLocs,
1336 OldMsg->getMethodDecl(),
1337 RHS,
1338 OldMsg->getRightLoc());
1339 break;
1340
1341 case ObjCMessageExpr::Instance:
1342 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1343 OldMsg->getValueKind(),
1344 OldMsg->getLeftLoc(),
1345 Base,
1346 OldMsg->getSelector(),
1347 SelLocs,
1348 OldMsg->getMethodDecl(),
1349 RHS,
1350 OldMsg->getRightLoc());
1351 break;
1352
1353 case ObjCMessageExpr::SuperClass:
1354 case ObjCMessageExpr::SuperInstance:
1355 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1356 OldMsg->getValueKind(),
1357 OldMsg->getLeftLoc(),
1358 OldMsg->getSuperLoc(),
1359 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1360 OldMsg->getSuperType(),
1361 OldMsg->getSelector(),
1362 SelLocs,
1363 OldMsg->getMethodDecl(),
1364 RHS,
1365 OldMsg->getRightLoc());
1366 break;
1367 }
1368
1369 Stmt *Replacement = SynthMessageExpr(NewMsg);
1370 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1371 return Replacement;
Steve Naroff15f081d2008-12-03 00:56:33 +00001372}
1373
John McCall4b9c2d22011-11-06 09:01:30 +00001374Stmt *RewriteObjC::RewritePropertyOrImplicitGetter(PseudoObjectExpr *PseudoOp) {
1375 SourceRange OldRange = PseudoOp->getSourceRange();
1376
1377 // We just magically know some things about the structure of this
1378 // expression.
1379 ObjCMessageExpr *OldMsg =
1380 cast<ObjCMessageExpr>(PseudoOp->getResultExpr()->IgnoreImplicit());
1381
1382 // Because the rewriter doesn't allow us to rewrite rewritten code,
1383 // we need to suppress rewriting the sub-statements.
1384 Expr *Base = 0;
1385 {
1386 DisableReplaceStmtScope S(*this);
1387
1388 // Rebuild the base expression if we have one.
1389 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1390 Base = OldMsg->getInstanceReceiver();
1391 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1392 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
John McCall12f78a62010-12-02 01:19:52 +00001393 }
Fariborz Jahaniane0f83862010-10-20 16:07:20 +00001394 }
Steve Naroff15f081d2008-12-03 00:56:33 +00001395
John McCall4b9c2d22011-11-06 09:01:30 +00001396 // Intentionally empty.
1397 SmallVector<SourceLocation, 1> SelLocs;
1398 SmallVector<Expr*, 1> Args;
Steve Naroff8599e7a2008-12-08 16:43:47 +00001399
John McCall4b9c2d22011-11-06 09:01:30 +00001400 ObjCMessageExpr *NewMsg;
1401 switch (OldMsg->getReceiverKind()) {
1402 case ObjCMessageExpr::Class:
1403 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1404 OldMsg->getValueKind(),
1405 OldMsg->getLeftLoc(),
1406 OldMsg->getClassReceiverTypeInfo(),
1407 OldMsg->getSelector(),
1408 SelLocs,
1409 OldMsg->getMethodDecl(),
1410 Args,
1411 OldMsg->getRightLoc());
1412 break;
1413
1414 case ObjCMessageExpr::Instance:
1415 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1416 OldMsg->getValueKind(),
1417 OldMsg->getLeftLoc(),
1418 Base,
1419 OldMsg->getSelector(),
1420 SelLocs,
1421 OldMsg->getMethodDecl(),
1422 Args,
1423 OldMsg->getRightLoc());
1424 break;
1425
1426 case ObjCMessageExpr::SuperClass:
1427 case ObjCMessageExpr::SuperInstance:
1428 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1429 OldMsg->getValueKind(),
1430 OldMsg->getLeftLoc(),
1431 OldMsg->getSuperLoc(),
1432 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1433 OldMsg->getSuperType(),
1434 OldMsg->getSelector(),
1435 SelLocs,
1436 OldMsg->getMethodDecl(),
1437 Args,
1438 OldMsg->getRightLoc());
1439 break;
Steve Naroff8599e7a2008-12-08 16:43:47 +00001440 }
John McCall4b9c2d22011-11-06 09:01:30 +00001441
1442 Stmt *Replacement = SynthMessageExpr(NewMsg);
1443 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1444 return Replacement;
Steve Naroff15f081d2008-12-03 00:56:33 +00001445}
1446
John McCall4b9c2d22011-11-06 09:01:30 +00001447Stmt *RewriteObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) {
1448 SourceRange OldRange = IV->getSourceRange();
1449 Expr *BaseExpr = IV->getBase();
1450
1451 // Rewrite the base, but without actually doing replaces.
1452 {
1453 DisableReplaceStmtScope S(*this);
1454 BaseExpr = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(BaseExpr));
1455 IV->setBase(BaseExpr);
1456 }
1457
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001458 ObjCIvarDecl *D = IV->getDecl();
John McCall4b9c2d22011-11-06 09:01:30 +00001459
1460 Expr *Replacement = IV;
Steve Naroff54055232008-10-27 17:20:55 +00001461 if (CurMethodDef) {
Fariborz Jahanian8f095432010-01-26 18:28:51 +00001462 if (BaseExpr->getType()->isObjCObjectPointerType()) {
John McCallf4c73712011-01-19 06:33:43 +00001463 const ObjCInterfaceType *iFaceDecl =
Fariborz Jahanian84ed6002010-01-07 18:18:32 +00001464 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
Fariborz Jahanianffbdead2010-01-26 20:37:44 +00001465 assert(iFaceDecl && "RewriteObjCIvarRefExpr - iFaceDecl is null");
Steve Narofff0757612008-05-08 17:52:16 +00001466 // lookup which class implements the instance variable.
1467 ObjCInterfaceDecl *clsDeclared = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001468 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
Douglas Gregor6ab35242009-04-09 21:40:53 +00001469 clsDeclared);
Steve Narofff0757612008-05-08 17:52:16 +00001470 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
Mike Stump1eb44332009-09-09 15:08:12 +00001471
Steve Narofff0757612008-05-08 17:52:16 +00001472 // Synthesize an explicit cast to gain access to the ivar.
1473 std::string RecName = clsDeclared->getIdentifier()->getName();
1474 RecName += "_IMPL";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001475 IdentifierInfo *II = &Context->Idents.get(RecName);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001476 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00001477 SourceLocation(), SourceLocation(),
1478 II);
Steve Narofff0757612008-05-08 17:52:16 +00001479 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1480 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
John McCall9d125032010-01-15 18:39:57 +00001481 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
John McCalla5bbc502010-11-15 09:46:46 +00001482 CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00001483 IV->getBase());
Steve Narofff0757612008-05-08 17:52:16 +00001484 // Don't forget the parens to enforce the proper binding.
John McCall4b9c2d22011-11-06 09:01:30 +00001485 ParenExpr *PE = new (Context) ParenExpr(OldRange.getBegin(),
1486 OldRange.getEnd(),
John McCallf89e55a2010-11-18 06:31:45 +00001487 castExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00001488 if (IV->isFreeIvar() &&
Steve Naroff54055232008-10-27 17:20:55 +00001489 CurMethodDef->getClassInterface() == iFaceDecl->getDecl()) {
Ted Kremenek8189cde2009-02-07 01:47:29 +00001490 MemberExpr *ME = new (Context) MemberExpr(PE, true, D,
John McCallf89e55a2010-11-18 06:31:45 +00001491 IV->getLocation(),
1492 D->getType(),
1493 VK_LValue, OK_Ordinary);
John McCall4b9c2d22011-11-06 09:01:30 +00001494 Replacement = ME;
1495 } else {
1496 IV->setBase(PE);
Steve Naroffc2a689b2007-11-15 11:33:00 +00001497 }
1498 }
Steve Naroff84472a82008-04-18 21:55:08 +00001499 } else { // we are outside a method.
Steve Naroff9f525972008-05-06 23:20:07 +00001500 assert(!IV->isFreeIvar() && "Cannot have a free standing ivar outside a method");
Mike Stump1eb44332009-09-09 15:08:12 +00001501
Steve Naroff9f525972008-05-06 23:20:07 +00001502 // Explicit ivar refs need to have a cast inserted.
1503 // FIXME: consider sharing some of this code with the code above.
Fariborz Jahanian26337b22010-01-12 17:31:23 +00001504 if (BaseExpr->getType()->isObjCObjectPointerType()) {
John McCallf4c73712011-01-19 06:33:43 +00001505 const ObjCInterfaceType *iFaceDecl =
Fariborz Jahanianc374cd92010-01-11 17:50:35 +00001506 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
Steve Naroff9f525972008-05-06 23:20:07 +00001507 // lookup which class implements the instance variable.
1508 ObjCInterfaceDecl *clsDeclared = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001509 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
Douglas Gregor6ab35242009-04-09 21:40:53 +00001510 clsDeclared);
Steve Naroff9f525972008-05-06 23:20:07 +00001511 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
Mike Stump1eb44332009-09-09 15:08:12 +00001512
Steve Naroff9f525972008-05-06 23:20:07 +00001513 // Synthesize an explicit cast to gain access to the ivar.
1514 std::string RecName = clsDeclared->getIdentifier()->getName();
1515 RecName += "_IMPL";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001516 IdentifierInfo *II = &Context->Idents.get(RecName);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001517 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00001518 SourceLocation(), SourceLocation(),
1519 II);
Steve Naroff9f525972008-05-06 23:20:07 +00001520 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1521 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
John McCall9d125032010-01-15 18:39:57 +00001522 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
John McCalla5bbc502010-11-15 09:46:46 +00001523 CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00001524 IV->getBase());
Steve Naroff9f525972008-05-06 23:20:07 +00001525 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00001526 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
Chris Lattner8d366162008-05-28 16:38:23 +00001527 IV->getBase()->getLocEnd(), castExpr);
Steve Naroff9f525972008-05-06 23:20:07 +00001528 // Cannot delete IV->getBase(), since PE points to it.
1529 // Replace the old base with the cast. This is important when doing
1530 // embedded rewrites. For example, [newInv->_container addObject:0].
Mike Stump1eb44332009-09-09 15:08:12 +00001531 IV->setBase(PE);
Steve Naroff9f525972008-05-06 23:20:07 +00001532 }
Steve Naroffc2a689b2007-11-15 11:33:00 +00001533 }
Steve Naroff7e3411b2007-11-15 02:58:25 +00001534
John McCall4b9c2d22011-11-06 09:01:30 +00001535 ReplaceStmtWithRange(IV, Replacement, OldRange);
1536 return Replacement;
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00001537}
1538
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001539/// SynthCountByEnumWithState - To print:
1540/// ((unsigned int (*)
1541/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump1eb44332009-09-09 15:08:12 +00001542/// (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001543/// sel_registerName(
Mike Stump1eb44332009-09-09 15:08:12 +00001544/// "countByEnumeratingWithState:objects:count:"),
1545/// &enumState,
Fariborz Jahanian108fb142011-11-09 17:41:43 +00001546/// (id *)__rw_items, (unsigned int)16)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001547///
Steve Naroffb29b4272008-04-14 22:03:09 +00001548void RewriteObjC::SynthCountByEnumWithState(std::string &buf) {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001549 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1550 "id *, unsigned int))(void *)objc_msgSend)";
1551 buf += "\n\t\t";
1552 buf += "((id)l_collection,\n\t\t";
1553 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1554 buf += "\n\t\t";
1555 buf += "&enumState, "
Fariborz Jahanian108fb142011-11-09 17:41:43 +00001556 "(id *)__rw_items, (unsigned int)16)";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001557}
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001558
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001559/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1560/// statement to exit to its outer synthesized loop.
1561///
Steve Naroffb29b4272008-04-14 22:03:09 +00001562Stmt *RewriteObjC::RewriteBreakStmt(BreakStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001563 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1564 return S;
1565 // replace break with goto __break_label
1566 std::string buf;
Mike Stump1eb44332009-09-09 15:08:12 +00001567
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001568 SourceLocation startLoc = S->getLocStart();
1569 buf = "goto __break_label_";
1570 buf += utostr(ObjCBcLabelNo.back());
Benjamin Kramerd999b372010-02-14 14:14:16 +00001571 ReplaceText(startLoc, strlen("break"), buf);
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001572
1573 return 0;
1574}
1575
1576/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1577/// statement to continue with its inner synthesized loop.
1578///
Steve Naroffb29b4272008-04-14 22:03:09 +00001579Stmt *RewriteObjC::RewriteContinueStmt(ContinueStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001580 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1581 return S;
1582 // replace continue with goto __continue_label
1583 std::string buf;
Mike Stump1eb44332009-09-09 15:08:12 +00001584
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001585 SourceLocation startLoc = S->getLocStart();
1586 buf = "goto __continue_label_";
1587 buf += utostr(ObjCBcLabelNo.back());
Benjamin Kramerd999b372010-02-14 14:14:16 +00001588 ReplaceText(startLoc, strlen("continue"), buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001589
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001590 return 0;
1591}
1592
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001593/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001594/// It rewrites:
1595/// for ( type elem in collection) { stmts; }
Mike Stump1eb44332009-09-09 15:08:12 +00001596
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001597/// Into:
1598/// {
Mike Stump1eb44332009-09-09 15:08:12 +00001599/// type elem;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001600/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahanian108fb142011-11-09 17:41:43 +00001601/// id __rw_items[16];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001602/// id l_collection = (id)collection;
Mike Stump1eb44332009-09-09 15:08:12 +00001603/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian108fb142011-11-09 17:41:43 +00001604/// objects:__rw_items count:16];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001605/// if (limit) {
1606/// unsigned long startMutations = *enumState.mutationsPtr;
1607/// do {
1608/// unsigned long counter = 0;
1609/// do {
Mike Stump1eb44332009-09-09 15:08:12 +00001610/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001611/// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001612/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001613/// stmts;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001614/// __continue_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001615/// } while (counter < limit);
Mike Stump1eb44332009-09-09 15:08:12 +00001616/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian108fb142011-11-09 17:41:43 +00001617/// objects:__rw_items count:16]);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001618/// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001619/// __break_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001620/// }
1621/// else
1622/// elem = nil;
1623/// }
1624///
Steve Naroffb29b4272008-04-14 22:03:09 +00001625Stmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
Chris Lattner338d1e22008-01-31 05:10:40 +00001626 SourceLocation OrigEnd) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001627 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
Mike Stump1eb44332009-09-09 15:08:12 +00001628 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001629 "ObjCForCollectionStmt Statement stack mismatch");
Mike Stump1eb44332009-09-09 15:08:12 +00001630 assert(!ObjCBcLabelNo.empty() &&
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001631 "ObjCForCollectionStmt - Label No stack empty");
Mike Stump1eb44332009-09-09 15:08:12 +00001632
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001633 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001634 const char *startBuf = SM->getCharacterData(startLoc);
Chris Lattner5f9e2722011-07-23 10:55:15 +00001635 StringRef elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001636 std::string elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001637 std::string buf;
1638 buf = "\n{\n\t";
1639 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1640 // type elem;
Chris Lattner7e24e822009-03-28 06:33:19 +00001641 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
Ted Kremenek1ed8e2a2008-10-06 22:16:13 +00001642 QualType ElementType = cast<ValueDecl>(D)->getType();
Steve Naroffe89b8e72009-12-04 21:18:19 +00001643 if (ElementType->isObjCQualifiedIdType() ||
1644 ElementType->isObjCQualifiedInterfaceType())
1645 // Simply use 'id' for all qualified types.
1646 elementTypeAsString = "id";
1647 else
Douglas Gregor30c42402011-09-27 22:38:19 +00001648 elementTypeAsString = ElementType.getAsString(Context->getPrintingPolicy());
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001649 buf += elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001650 buf += " ";
Daniel Dunbar4087f272010-08-17 22:39:59 +00001651 elementName = D->getName();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001652 buf += elementName;
1653 buf += ";\n\t";
1654 }
Chris Lattner06767512008-04-08 05:52:18 +00001655 else {
1656 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
Daniel Dunbar4087f272010-08-17 22:39:59 +00001657 elementName = DR->getDecl()->getName();
Steve Naroffe89b8e72009-12-04 21:18:19 +00001658 ValueDecl *VD = cast<ValueDecl>(DR->getDecl());
1659 if (VD->getType()->isObjCQualifiedIdType() ||
1660 VD->getType()->isObjCQualifiedInterfaceType())
1661 // Simply use 'id' for all qualified types.
1662 elementTypeAsString = "id";
1663 else
Douglas Gregor30c42402011-09-27 22:38:19 +00001664 elementTypeAsString = VD->getType().getAsString(Context->getPrintingPolicy());
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001665 }
Mike Stump1eb44332009-09-09 15:08:12 +00001666
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001667 // struct __objcFastEnumerationState enumState = { 0 };
1668 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
Fariborz Jahanian108fb142011-11-09 17:41:43 +00001669 // id __rw_items[16];
1670 buf += "id __rw_items[16];\n\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001671 // id l_collection = (id)
1672 buf += "id l_collection = (id)";
Fariborz Jahanian75712282008-01-10 00:24:29 +00001673 // Find start location of 'collection' the hard way!
1674 const char *startCollectionBuf = startBuf;
1675 startCollectionBuf += 3; // skip 'for'
1676 startCollectionBuf = strchr(startCollectionBuf, '(');
1677 startCollectionBuf++; // skip '('
1678 // find 'in' and skip it.
1679 while (*startCollectionBuf != ' ' ||
1680 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1681 (*(startCollectionBuf+3) != ' ' &&
1682 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1683 startCollectionBuf++;
1684 startCollectionBuf += 3;
Mike Stump1eb44332009-09-09 15:08:12 +00001685
1686 // Replace: "for (type element in" with string constructed thus far.
Benjamin Kramerd999b372010-02-14 14:14:16 +00001687 ReplaceText(startLoc, startCollectionBuf - startBuf, buf);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001688 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahanian75712282008-01-10 00:24:29 +00001689 SourceLocation rightParenLoc = S->getRParenLoc();
1690 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001691 SourceLocation lparenLoc = startLoc.getLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001692 buf = ";\n\t";
Mike Stump1eb44332009-09-09 15:08:12 +00001693
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001694 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian108fb142011-11-09 17:41:43 +00001695 // objects:__rw_items count:16];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001696 // which is synthesized into:
Mike Stump1eb44332009-09-09 15:08:12 +00001697 // unsigned int limit =
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001698 // ((unsigned int (*)
1699 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump1eb44332009-09-09 15:08:12 +00001700 // (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001701 // sel_registerName(
Mike Stump1eb44332009-09-09 15:08:12 +00001702 // "countByEnumeratingWithState:objects:count:"),
1703 // (struct __objcFastEnumerationState *)&state,
Fariborz Jahanian108fb142011-11-09 17:41:43 +00001704 // (id *)__rw_items, (unsigned int)16);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001705 buf += "unsigned long limit =\n\t\t";
1706 SynthCountByEnumWithState(buf);
1707 buf += ";\n\t";
1708 /// if (limit) {
1709 /// unsigned long startMutations = *enumState.mutationsPtr;
1710 /// do {
1711 /// unsigned long counter = 0;
1712 /// do {
Mike Stump1eb44332009-09-09 15:08:12 +00001713 /// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001714 /// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001715 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001716 buf += "if (limit) {\n\t";
1717 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1718 buf += "do {\n\t\t";
1719 buf += "unsigned long counter = 0;\n\t\t";
1720 buf += "do {\n\t\t\t";
1721 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1722 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1723 buf += elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001724 buf += " = (";
1725 buf += elementTypeAsString;
1726 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001727 // Replace ')' in for '(' type elem in collection ')' with all of these.
Benjamin Kramerd999b372010-02-14 14:14:16 +00001728 ReplaceText(lparenLoc, 1, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001729
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001730 /// __continue_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001731 /// } while (counter < limit);
Mike Stump1eb44332009-09-09 15:08:12 +00001732 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian108fb142011-11-09 17:41:43 +00001733 /// objects:__rw_items count:16]);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001734 /// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001735 /// __break_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001736 /// }
1737 /// else
1738 /// elem = nil;
1739 /// }
Mike Stump1eb44332009-09-09 15:08:12 +00001740 ///
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001741 buf = ";\n\t";
1742 buf += "__continue_label_";
1743 buf += utostr(ObjCBcLabelNo.back());
1744 buf += ": ;";
1745 buf += "\n\t\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001746 buf += "} while (counter < limit);\n\t";
1747 buf += "} while (limit = ";
1748 SynthCountByEnumWithState(buf);
1749 buf += ");\n\t";
1750 buf += elementName;
Fariborz Jahanian65b0aa52010-01-08 01:29:44 +00001751 buf += " = ((";
1752 buf += elementTypeAsString;
1753 buf += ")0);\n\t";
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001754 buf += "__break_label_";
1755 buf += utostr(ObjCBcLabelNo.back());
1756 buf += ": ;\n\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001757 buf += "}\n\t";
1758 buf += "else\n\t\t";
1759 buf += elementName;
Fariborz Jahanian65b0aa52010-01-08 01:29:44 +00001760 buf += " = ((";
1761 buf += elementTypeAsString;
1762 buf += ")0);\n\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001763 buf += "}\n";
Mike Stump1eb44332009-09-09 15:08:12 +00001764
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001765 // Insert all these *after* the statement body.
Sebastian Redld3a413d2009-04-26 20:35:05 +00001766 // FIXME: If this should support Obj-C++, support CXXTryStmt
Steve Naroff600e4e82008-07-21 18:26:02 +00001767 if (isa<CompoundStmt>(S->getBody())) {
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001768 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001769 InsertText(endBodyLoc, buf);
Steve Naroff600e4e82008-07-21 18:26:02 +00001770 } else {
1771 /* Need to treat single statements specially. For example:
1772 *
1773 * for (A *a in b) if (stuff()) break;
1774 * for (A *a in b) xxxyy;
1775 *
1776 * The following code simply scans ahead to the semi to find the actual end.
1777 */
1778 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1779 const char *semiBuf = strchr(stmtBuf, ';');
1780 assert(semiBuf && "Can't find ';'");
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001781 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(semiBuf-stmtBuf+1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001782 InsertText(endBodyLoc, buf);
Steve Naroff600e4e82008-07-21 18:26:02 +00001783 }
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001784 Stmts.pop_back();
1785 ObjCBcLabelNo.pop_back();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001786 return 0;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001787}
1788
Mike Stump1eb44332009-09-09 15:08:12 +00001789/// RewriteObjCSynchronizedStmt -
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001790/// This routine rewrites @synchronized(expr) stmt;
1791/// into:
1792/// objc_sync_enter(expr);
1793/// @try stmt @finally { objc_sync_exit(expr); }
1794///
Steve Naroffb29b4272008-04-14 22:03:09 +00001795Stmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001796 // Get the start location and compute the semi location.
1797 SourceLocation startLoc = S->getLocStart();
1798 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001799
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001800 assert((*startBuf == '@') && "bogus @synchronized location");
Mike Stump1eb44332009-09-09 15:08:12 +00001801
1802 std::string buf;
Steve Naroff3498cc92008-08-21 13:03:03 +00001803 buf = "objc_sync_enter((id)";
1804 const char *lparenBuf = startBuf;
1805 while (*lparenBuf != '(') lparenBuf++;
Benjamin Kramerd999b372010-02-14 14:14:16 +00001806 ReplaceText(startLoc, lparenBuf-startBuf+1, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001807 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1808 // the sync expression is typically a message expression that's already
Steve Naroffc7089f12008-08-19 13:04:19 +00001809 // been rewritten! (which implies the SourceLocation's are invalid).
1810 SourceLocation endLoc = S->getSynchBody()->getLocStart();
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001811 const char *endBuf = SM->getCharacterData(endLoc);
Steve Naroffc7089f12008-08-19 13:04:19 +00001812 while (*endBuf != ')') endBuf--;
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001813 SourceLocation rparenLoc = startLoc.getLocWithOffset(endBuf-startBuf);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001814 buf = ");\n";
1815 // declare a new scope with two variables, _stack and _rethrow.
1816 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1817 buf += "int buf[18/*32-bit i386*/];\n";
1818 buf += "char *pointers[4];} _stack;\n";
1819 buf += "id volatile _rethrow = 0;\n";
1820 buf += "objc_exception_try_enter(&_stack);\n";
1821 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001822 ReplaceText(rparenLoc, 1, buf);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001823 startLoc = S->getSynchBody()->getLocEnd();
1824 startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001825
Steve Naroffc7089f12008-08-19 13:04:19 +00001826 assert((*startBuf == '}') && "bogus @synchronized block");
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001827 SourceLocation lastCurlyLoc = startLoc;
1828 buf = "}\nelse {\n";
1829 buf += " _rethrow = objc_exception_extract(&_stack);\n";
Steve Naroff621edce2009-04-29 16:37:50 +00001830 buf += "}\n";
1831 buf += "{ /* implicit finally clause */\n";
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001832 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Steve Naroffb85e77a2009-12-05 21:43:12 +00001833
1834 std::string syncBuf;
1835 syncBuf += " objc_sync_exit(";
John McCall1d9b3b22011-09-09 05:25:32 +00001836
1837 Expr *syncExpr = S->getSynchExpr();
1838 CastKind CK = syncExpr->getType()->isObjCObjectPointerType()
1839 ? CK_BitCast :
1840 syncExpr->getType()->isBlockPointerType()
1841 ? CK_BlockPointerToObjCPointerCast
1842 : CK_CPointerToObjCPointerCast;
1843 syncExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
1844 CK, syncExpr);
Ted Kremeneka95d3752008-09-13 05:16:45 +00001845 std::string syncExprBufS;
1846 llvm::raw_string_ostream syncExprBuf(syncExprBufS);
Chris Lattnere4f21422009-06-30 01:26:17 +00001847 syncExpr->printPretty(syncExprBuf, *Context, 0,
1848 PrintingPolicy(LangOpts));
Steve Naroffb85e77a2009-12-05 21:43:12 +00001849 syncBuf += syncExprBuf.str();
1850 syncBuf += ");";
1851
1852 buf += syncBuf;
1853 buf += "\n if (_rethrow) objc_exception_throw(_rethrow);\n";
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001854 buf += "}\n";
1855 buf += "}";
Mike Stump1eb44332009-09-09 15:08:12 +00001856
Benjamin Kramerd999b372010-02-14 14:14:16 +00001857 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffb85e77a2009-12-05 21:43:12 +00001858
1859 bool hasReturns = false;
1860 HasReturnStmts(S->getSynchBody(), hasReturns);
1861 if (hasReturns)
1862 RewriteSyncReturnStmts(S->getSynchBody(), syncBuf);
1863
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001864 return 0;
1865}
1866
Steve Naroffb85e77a2009-12-05 21:43:12 +00001867void RewriteObjC::WarnAboutReturnGotoStmts(Stmt *S)
1868{
Steve Naroff8c565152008-12-05 17:03:39 +00001869 // Perform a bottom up traversal of all children.
John McCall7502c1d2011-02-13 04:07:26 +00001870 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroff8c565152008-12-05 17:03:39 +00001871 if (*CI)
Steve Naroffb85e77a2009-12-05 21:43:12 +00001872 WarnAboutReturnGotoStmts(*CI);
Steve Naroff8c565152008-12-05 17:03:39 +00001873
Steve Naroffb85e77a2009-12-05 21:43:12 +00001874 if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001875 Diags.Report(Context->getFullLoc(S->getLocStart()),
Steve Naroff8c565152008-12-05 17:03:39 +00001876 TryFinallyContainsReturnDiag);
1877 }
1878 return;
1879}
1880
Steve Naroffb85e77a2009-12-05 21:43:12 +00001881void RewriteObjC::HasReturnStmts(Stmt *S, bool &hasReturns)
1882{
1883 // Perform a bottom up traversal of all children.
John McCall7502c1d2011-02-13 04:07:26 +00001884 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroffb85e77a2009-12-05 21:43:12 +00001885 if (*CI)
1886 HasReturnStmts(*CI, hasReturns);
1887
1888 if (isa<ReturnStmt>(S))
1889 hasReturns = true;
1890 return;
1891}
1892
1893void RewriteObjC::RewriteTryReturnStmts(Stmt *S) {
1894 // Perform a bottom up traversal of all children.
John McCall7502c1d2011-02-13 04:07:26 +00001895 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroffb85e77a2009-12-05 21:43:12 +00001896 if (*CI) {
1897 RewriteTryReturnStmts(*CI);
1898 }
1899 if (isa<ReturnStmt>(S)) {
1900 SourceLocation startLoc = S->getLocStart();
1901 const char *startBuf = SM->getCharacterData(startLoc);
1902
1903 const char *semiBuf = strchr(startBuf, ';');
1904 assert((*semiBuf == ';') && "RewriteTryReturnStmts: can't find ';'");
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001905 SourceLocation onePastSemiLoc = startLoc.getLocWithOffset(semiBuf-startBuf+1);
Steve Naroffb85e77a2009-12-05 21:43:12 +00001906
1907 std::string buf;
1908 buf = "{ objc_exception_try_exit(&_stack); return";
1909
Benjamin Kramerd999b372010-02-14 14:14:16 +00001910 ReplaceText(startLoc, 6, buf);
1911 InsertText(onePastSemiLoc, "}");
Steve Naroffb85e77a2009-12-05 21:43:12 +00001912 }
1913 return;
1914}
1915
1916void RewriteObjC::RewriteSyncReturnStmts(Stmt *S, std::string syncExitBuf) {
1917 // Perform a bottom up traversal of all children.
John McCall7502c1d2011-02-13 04:07:26 +00001918 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroffb85e77a2009-12-05 21:43:12 +00001919 if (*CI) {
1920 RewriteSyncReturnStmts(*CI, syncExitBuf);
1921 }
1922 if (isa<ReturnStmt>(S)) {
1923 SourceLocation startLoc = S->getLocStart();
1924 const char *startBuf = SM->getCharacterData(startLoc);
1925
1926 const char *semiBuf = strchr(startBuf, ';');
1927 assert((*semiBuf == ';') && "RewriteSyncReturnStmts: can't find ';'");
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001928 SourceLocation onePastSemiLoc = startLoc.getLocWithOffset(semiBuf-startBuf+1);
Steve Naroffb85e77a2009-12-05 21:43:12 +00001929
1930 std::string buf;
1931 buf = "{ objc_exception_try_exit(&_stack);";
1932 buf += syncExitBuf;
1933 buf += " return";
1934
Benjamin Kramerd999b372010-02-14 14:14:16 +00001935 ReplaceText(startLoc, 6, buf);
1936 InsertText(onePastSemiLoc, "}");
Steve Naroffb85e77a2009-12-05 21:43:12 +00001937 }
1938 return;
1939}
1940
Steve Naroffb29b4272008-04-14 22:03:09 +00001941Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroff75730982007-11-07 04:08:17 +00001942 // Get the start location and compute the semi location.
1943 SourceLocation startLoc = S->getLocStart();
1944 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001945
Steve Naroff75730982007-11-07 04:08:17 +00001946 assert((*startBuf == '@') && "bogus @try location");
1947
1948 std::string buf;
1949 // declare a new scope with two variables, _stack and _rethrow.
1950 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1951 buf += "int buf[18/*32-bit i386*/];\n";
1952 buf += "char *pointers[4];} _stack;\n";
1953 buf += "id volatile _rethrow = 0;\n";
1954 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +00001955 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroff75730982007-11-07 04:08:17 +00001956
Benjamin Kramerd999b372010-02-14 14:14:16 +00001957 ReplaceText(startLoc, 4, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001958
Steve Naroff75730982007-11-07 04:08:17 +00001959 startLoc = S->getTryBody()->getLocEnd();
1960 startBuf = SM->getCharacterData(startLoc);
1961
1962 assert((*startBuf == '}') && "bogus @try block");
Mike Stump1eb44332009-09-09 15:08:12 +00001963
Steve Naroff75730982007-11-07 04:08:17 +00001964 SourceLocation lastCurlyLoc = startLoc;
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001965 if (S->getNumCatchStmts()) {
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001966 startLoc = startLoc.getLocWithOffset(1);
Steve Naroffc9ba1722008-07-16 15:31:30 +00001967 buf = " /* @catch begin */ else {\n";
1968 buf += " id _caught = objc_exception_extract(&_stack);\n";
1969 buf += " objc_exception_try_enter (&_stack);\n";
1970 buf += " if (_setjmp(_stack.buf))\n";
1971 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1972 buf += " else { /* @catch continue */";
Mike Stump1eb44332009-09-09 15:08:12 +00001973
Benjamin Kramerd999b372010-02-14 14:14:16 +00001974 InsertText(startLoc, buf);
Steve Naroff8bd3dc62008-09-09 19:59:12 +00001975 } else { /* no catch list */
1976 buf = "}\nelse {\n";
1977 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1978 buf += "}";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001979 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffc9ba1722008-07-16 15:31:30 +00001980 }
Steve Naroff75730982007-11-07 04:08:17 +00001981 Stmt *lastCatchBody = 0;
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001982 for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
1983 ObjCAtCatchStmt *Catch = S->getCatchStmt(I);
Douglas Gregorc00d8e12010-04-26 16:46:50 +00001984 VarDecl *catchDecl = Catch->getCatchParamDecl();
Steve Naroff75730982007-11-07 04:08:17 +00001985
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001986 if (I == 0)
Steve Naroff75730982007-11-07 04:08:17 +00001987 buf = "if ("; // we are generating code for the first catch clause
1988 else
1989 buf = "else if (";
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001990 startLoc = Catch->getLocStart();
Steve Naroff75730982007-11-07 04:08:17 +00001991 startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001992
Steve Naroff75730982007-11-07 04:08:17 +00001993 assert((*startBuf == '@') && "bogus @catch location");
Mike Stump1eb44332009-09-09 15:08:12 +00001994
Steve Naroff75730982007-11-07 04:08:17 +00001995 const char *lParenLoc = strchr(startBuf, '(');
1996
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001997 if (Catch->hasEllipsis()) {
Steve Naroffe12e6922008-02-01 20:02:07 +00001998 // Now rewrite the body...
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001999 lastCatchBody = Catch->getCatchBody();
Steve Naroffe12e6922008-02-01 20:02:07 +00002000 SourceLocation bodyLoc = lastCatchBody->getLocStart();
2001 const char *bodyBuf = SM->getCharacterData(bodyLoc);
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00002002 assert(*SM->getCharacterData(Catch->getRParenLoc()) == ')' &&
Chris Lattner06767512008-04-08 05:52:18 +00002003 "bogus @catch paren location");
Steve Naroffe12e6922008-02-01 20:02:07 +00002004 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump1eb44332009-09-09 15:08:12 +00002005
Steve Naroffe12e6922008-02-01 20:02:07 +00002006 buf += "1) { id _tmp = _caught;";
Daniel Dunbard7407dc2009-08-19 19:10:30 +00002007 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1, buf);
Steve Naroff7ba138a2009-03-03 19:52:17 +00002008 } else if (catchDecl) {
2009 QualType t = catchDecl->getType();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002010 if (t == Context->getObjCIdType()) {
Steve Naroff75730982007-11-07 04:08:17 +00002011 buf += "1) { ";
Benjamin Kramerd999b372010-02-14 14:14:16 +00002012 ReplaceText(startLoc, lParenLoc-startBuf+1, buf);
John McCall506b57e2010-05-17 21:00:27 +00002013 } else if (const ObjCObjectPointerType *Ptr =
2014 t->getAs<ObjCObjectPointerType>()) {
2015 // Should be a pointer to a class.
2016 ObjCInterfaceDecl *IDecl = Ptr->getObjectType()->getInterface();
2017 if (IDecl) {
Steve Naroff21867b12007-11-07 18:43:40 +00002018 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
John McCall506b57e2010-05-17 21:00:27 +00002019 buf += IDecl->getNameAsString();
Steve Naroff21867b12007-11-07 18:43:40 +00002020 buf += "\"), (struct objc_object *)_caught)) { ";
Benjamin Kramerd999b372010-02-14 14:14:16 +00002021 ReplaceText(startLoc, lParenLoc-startBuf+1, buf);
Steve Naroff75730982007-11-07 04:08:17 +00002022 }
2023 }
2024 // Now rewrite the body...
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00002025 lastCatchBody = Catch->getCatchBody();
2026 SourceLocation rParenLoc = Catch->getRParenLoc();
Steve Naroff75730982007-11-07 04:08:17 +00002027 SourceLocation bodyLoc = lastCatchBody->getLocStart();
2028 const char *bodyBuf = SM->getCharacterData(bodyLoc);
2029 const char *rParenBuf = SM->getCharacterData(rParenLoc);
2030 assert((*rParenBuf == ')') && "bogus @catch paren location");
2031 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump1eb44332009-09-09 15:08:12 +00002032
Mike Stump1eb44332009-09-09 15:08:12 +00002033 // Here we replace ") {" with "= _caught;" (which initializes and
Steve Naroff75730982007-11-07 04:08:17 +00002034 // declares the @catch parameter).
Benjamin Kramerd999b372010-02-14 14:14:16 +00002035 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, " = _caught;");
Steve Naroff7ba138a2009-03-03 19:52:17 +00002036 } else {
David Blaikieb219cfc2011-09-23 05:06:16 +00002037 llvm_unreachable("@catch rewrite bug");
Steve Naroff2bd03922007-11-07 15:32:26 +00002038 }
Steve Naroff75730982007-11-07 04:08:17 +00002039 }
2040 // Complete the catch list...
2041 if (lastCatchBody) {
2042 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00002043 assert(*SM->getCharacterData(bodyLoc) == '}' &&
2044 "bogus @catch body location");
Mike Stump1eb44332009-09-09 15:08:12 +00002045
Steve Naroff378f47a2008-09-11 15:29:03 +00002046 // Insert the last (implicit) else clause *before* the right curly brace.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00002047 bodyLoc = bodyLoc.getLocWithOffset(-1);
Steve Naroff378f47a2008-09-11 15:29:03 +00002048 buf = "} /* last catch end */\n";
2049 buf += "else {\n";
2050 buf += " _rethrow = _caught;\n";
2051 buf += " objc_exception_try_exit(&_stack);\n";
2052 buf += "} } /* @catch end */\n";
2053 if (!S->getFinallyStmt())
2054 buf += "}\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00002055 InsertText(bodyLoc, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00002056
Steve Naroff75730982007-11-07 04:08:17 +00002057 // Set lastCurlyLoc
2058 lastCurlyLoc = lastCatchBody->getLocEnd();
2059 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002060 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroff75730982007-11-07 04:08:17 +00002061 startLoc = finalStmt->getLocStart();
2062 startBuf = SM->getCharacterData(startLoc);
2063 assert((*startBuf == '@') && "bogus @finally start");
Mike Stump1eb44332009-09-09 15:08:12 +00002064
Benjamin Kramerd999b372010-02-14 14:14:16 +00002065 ReplaceText(startLoc, 8, "/* @finally */");
Mike Stump1eb44332009-09-09 15:08:12 +00002066
Steve Naroff75730982007-11-07 04:08:17 +00002067 Stmt *body = finalStmt->getFinallyBody();
2068 SourceLocation startLoc = body->getLocStart();
2069 SourceLocation endLoc = body->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00002070 assert(*SM->getCharacterData(startLoc) == '{' &&
2071 "bogus @finally body location");
Mike Stump1eb44332009-09-09 15:08:12 +00002072 assert(*SM->getCharacterData(endLoc) == '}' &&
Chris Lattner06767512008-04-08 05:52:18 +00002073 "bogus @finally body location");
Mike Stump1eb44332009-09-09 15:08:12 +00002074
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00002075 startLoc = startLoc.getLocWithOffset(1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002076 InsertText(startLoc, " if (!_rethrow) objc_exception_try_exit(&_stack);\n");
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00002077 endLoc = endLoc.getLocWithOffset(-1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002078 InsertText(endLoc, " if (_rethrow) objc_exception_throw(_rethrow);\n");
Mike Stump1eb44332009-09-09 15:08:12 +00002079
Steve Naroff75730982007-11-07 04:08:17 +00002080 // Set lastCurlyLoc
2081 lastCurlyLoc = body->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +00002082
Steve Naroff8c565152008-12-05 17:03:39 +00002083 // Now check for any return/continue/go statements within the @try.
Steve Naroffb85e77a2009-12-05 21:43:12 +00002084 WarnAboutReturnGotoStmts(S->getTryBody());
Steve Naroff378f47a2008-09-11 15:29:03 +00002085 } else { /* no finally clause - make sure we synthesize an implicit one */
2086 buf = "{ /* implicit finally clause */\n";
2087 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
2088 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
2089 buf += "}";
Benjamin Kramerd999b372010-02-14 14:14:16 +00002090 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffb85e77a2009-12-05 21:43:12 +00002091
2092 // Now check for any return/continue/go statements within the @try.
2093 // The implicit finally clause won't called if the @try contains any
2094 // jump statements.
2095 bool hasReturns = false;
2096 HasReturnStmts(S->getTryBody(), hasReturns);
2097 if (hasReturns)
2098 RewriteTryReturnStmts(S->getTryBody());
Steve Naroff75730982007-11-07 04:08:17 +00002099 }
2100 // Now emit the final closing curly brace...
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00002101 lastCurlyLoc = lastCurlyLoc.getLocWithOffset(1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002102 InsertText(lastCurlyLoc, " } /* @try scope end */\n");
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00002103 return 0;
2104}
2105
Mike Stump1eb44332009-09-09 15:08:12 +00002106// This can't be done with ReplaceStmt(S, ThrowExpr), since
2107// the throw expression is typically a message expression that's already
Steve Naroff2bd03922007-11-07 15:32:26 +00002108// been rewritten! (which implies the SourceLocation's are invalid).
Steve Naroffb29b4272008-04-14 22:03:09 +00002109Stmt *RewriteObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroff2bd03922007-11-07 15:32:26 +00002110 // Get the start location and compute the semi location.
2111 SourceLocation startLoc = S->getLocStart();
2112 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00002113
Steve Naroff2bd03922007-11-07 15:32:26 +00002114 assert((*startBuf == '@') && "bogus @throw location");
2115
2116 std::string buf;
2117 /* void objc_exception_throw(id) __attribute__((noreturn)); */
Steve Naroff20ebf8f2008-01-19 00:42:38 +00002118 if (S->getThrowExpr())
2119 buf = "objc_exception_throw(";
2120 else // add an implicit argument
2121 buf = "objc_exception_throw(_caught";
Mike Stump1eb44332009-09-09 15:08:12 +00002122
Steve Naroff4ba0acb2008-07-25 15:41:30 +00002123 // handle "@ throw" correctly.
2124 const char *wBuf = strchr(startBuf, 'w');
2125 assert((*wBuf == 'w') && "@throw: can't find 'w'");
Benjamin Kramerd999b372010-02-14 14:14:16 +00002126 ReplaceText(startLoc, wBuf-startBuf+1, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00002127
Steve Naroff2bd03922007-11-07 15:32:26 +00002128 const char *semiBuf = strchr(startBuf, ';');
2129 assert((*semiBuf == ';') && "@throw: can't find ';'");
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00002130 SourceLocation semiLoc = startLoc.getLocWithOffset(semiBuf-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002131 ReplaceText(semiLoc, 1, ");");
Steve Naroff2bd03922007-11-07 15:32:26 +00002132 return 0;
2133}
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00002134
Steve Naroffb29b4272008-04-14 22:03:09 +00002135Stmt *RewriteObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattner01c57482007-10-17 22:35:30 +00002136 // Create a new string expression.
2137 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002138 std::string StrEncoding;
Daniel Dunbar0d504c12008-10-17 20:21:44 +00002139 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
Jay Foad65aa6882011-06-21 15:13:30 +00002140 Expr *Replacement = StringLiteral::Create(*Context, StrEncoding,
Douglas Gregor5cee1192011-07-27 05:40:30 +00002141 StringLiteral::Ascii, false,
2142 StrType, SourceLocation());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002143 ReplaceStmt(Exp, Replacement);
Mike Stump1eb44332009-09-09 15:08:12 +00002144
Chris Lattner07506182007-11-30 22:53:43 +00002145 // Replace this subexpr in the parent.
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00002146 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Chris Lattnere64b7772007-10-24 16:57:36 +00002147 return Replacement;
Chris Lattner311ff022007-10-16 22:36:42 +00002148}
2149
Steve Naroffb29b4272008-04-14 22:03:09 +00002150Stmt *RewriteObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
Steve Naroff1a937642008-12-22 22:16:07 +00002151 if (!SelGetUidFunctionDecl)
2152 SynthSelGetUidFunctionDecl();
Steve Naroffb42f8412007-11-05 14:50:49 +00002153 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
2154 // Create a call to sel_registerName("selName").
Chris Lattner5f9e2722011-07-23 10:55:15 +00002155 SmallVector<Expr*, 8> SelExprs;
Steve Naroffb42f8412007-11-05 14:50:49 +00002156 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump1eb44332009-09-09 15:08:12 +00002157 SelExprs.push_back(StringLiteral::Create(*Context,
Jay Foad65aa6882011-06-21 15:13:30 +00002158 Exp->getSelector().getAsString(),
Douglas Gregor5cee1192011-07-27 05:40:30 +00002159 StringLiteral::Ascii, false,
2160 argType, SourceLocation()));
Steve Naroffb42f8412007-11-05 14:50:49 +00002161 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2162 &SelExprs[0], SelExprs.size());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002163 ReplaceStmt(Exp, SelExp);
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00002164 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroffb42f8412007-11-05 14:50:49 +00002165 return SelExp;
2166}
2167
Steve Naroffb29b4272008-04-14 22:03:09 +00002168CallExpr *RewriteObjC::SynthesizeCallToFunctionDecl(
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002169 FunctionDecl *FD, Expr **args, unsigned nargs, SourceLocation StartLoc,
2170 SourceLocation EndLoc) {
Steve Naroffebf2b562007-10-23 23:50:29 +00002171 // Get the type, we will need to reference it in a couple spots.
Steve Naroff934f2762007-10-24 22:48:43 +00002172 QualType msgSendType = FD->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002173
Steve Naroffebf2b562007-10-23 23:50:29 +00002174 // Create a reference to the objc_msgSend() declaration.
John McCallf89e55a2010-11-18 06:31:45 +00002175 DeclRefExpr *DRE =
2176 new (Context) DeclRefExpr(FD, msgSendType, VK_LValue, SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00002177
Steve Naroffebf2b562007-10-23 23:50:29 +00002178 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerf04da132007-10-24 17:06:59 +00002179 QualType pToFunc = Context->getPointerType(msgSendType);
Anders Carlsson88465d32010-04-23 22:18:37 +00002180 ImplicitCastExpr *ICE =
John McCalla5bbc502010-11-15 09:46:46 +00002181 ImplicitCastExpr::Create(*Context, pToFunc, CK_FunctionToPointerDecay,
John McCall5baba9d2010-08-25 10:28:54 +00002182 DRE, 0, VK_RValue);
Mike Stump1eb44332009-09-09 15:08:12 +00002183
John McCall183700f2009-09-21 23:43:11 +00002184 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Mike Stump1eb44332009-09-09 15:08:12 +00002185
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002186 CallExpr *Exp =
Douglas Gregor5291c3c2010-07-13 08:18:22 +00002187 new (Context) CallExpr(*Context, ICE, args, nargs,
John McCallf89e55a2010-11-18 06:31:45 +00002188 FT->getCallResultType(*Context),
2189 VK_RValue, EndLoc);
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002190 return Exp;
Steve Naroff934f2762007-10-24 22:48:43 +00002191}
2192
Steve Naroffd5255f52007-11-01 13:24:47 +00002193static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
2194 const char *&startRef, const char *&endRef) {
2195 while (startBuf < endBuf) {
2196 if (*startBuf == '<')
2197 startRef = startBuf; // mark the start.
2198 if (*startBuf == '>') {
Steve Naroff32174822007-11-09 12:50:28 +00002199 if (startRef && *startRef == '<') {
2200 endRef = startBuf; // mark the end.
2201 return true;
2202 }
2203 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +00002204 }
2205 startBuf++;
2206 }
2207 return false;
2208}
2209
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002210static void scanToNextArgument(const char *&argRef) {
2211 int angle = 0;
2212 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
2213 if (*argRef == '<')
2214 angle++;
2215 else if (*argRef == '>')
2216 angle--;
2217 argRef++;
2218 }
2219 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
2220}
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00002221
Steve Naroffb29b4272008-04-14 22:03:09 +00002222bool RewriteObjC::needToScanForQualifiers(QualType T) {
Fariborz Jahanian32132a02010-02-03 21:29:28 +00002223 if (T->isObjCQualifiedIdType())
2224 return true;
Fariborz Jahanian84aa9462010-02-02 18:35:07 +00002225 if (const PointerType *PT = T->getAs<PointerType>()) {
2226 if (PT->getPointeeType()->isObjCQualifiedIdType())
2227 return true;
2228 }
2229 if (T->isObjCObjectPointerType()) {
2230 T = T->getPointeeType();
2231 return T->isObjCQualifiedInterfaceType();
2232 }
Fariborz Jahanian24f9cab2010-09-30 20:41:32 +00002233 if (T->isArrayType()) {
2234 QualType ElemTy = Context->getBaseElementType(T);
2235 return needToScanForQualifiers(ElemTy);
2236 }
Fariborz Jahanian84aa9462010-02-02 18:35:07 +00002237 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +00002238}
2239
Steve Naroff4f95b752008-07-29 18:15:38 +00002240void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
2241 QualType Type = E->getType();
2242 if (needToScanForQualifiers(Type)) {
Steve Naroffcda658e2008-11-19 21:15:47 +00002243 SourceLocation Loc, EndLoc;
Mike Stump1eb44332009-09-09 15:08:12 +00002244
Steve Naroffcda658e2008-11-19 21:15:47 +00002245 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
2246 Loc = ECE->getLParenLoc();
2247 EndLoc = ECE->getRParenLoc();
2248 } else {
2249 Loc = E->getLocStart();
2250 EndLoc = E->getLocEnd();
2251 }
2252 // This will defend against trying to rewrite synthesized expressions.
2253 if (Loc.isInvalid() || EndLoc.isInvalid())
2254 return;
2255
Steve Naroff4f95b752008-07-29 18:15:38 +00002256 const char *startBuf = SM->getCharacterData(Loc);
Steve Naroffcda658e2008-11-19 21:15:47 +00002257 const char *endBuf = SM->getCharacterData(EndLoc);
Steve Naroff4f95b752008-07-29 18:15:38 +00002258 const char *startRef = 0, *endRef = 0;
2259 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2260 // Get the locations of the startRef, endRef.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00002261 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-startBuf);
2262 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-startBuf+1);
Steve Naroff4f95b752008-07-29 18:15:38 +00002263 // Comment out the protocol references.
Benjamin Kramerd999b372010-02-14 14:14:16 +00002264 InsertText(LessLoc, "/*");
2265 InsertText(GreaterLoc, "*/");
Steve Naroff4f95b752008-07-29 18:15:38 +00002266 }
2267 }
2268}
2269
Steve Naroffb29b4272008-04-14 22:03:09 +00002270void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002271 SourceLocation Loc;
2272 QualType Type;
Douglas Gregor72564e72009-02-26 23:50:07 +00002273 const FunctionProtoType *proto = 0;
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002274 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
2275 Loc = VD->getLocation();
2276 Type = VD->getType();
2277 }
2278 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2279 Loc = FD->getLocation();
2280 // Check for ObjC 'id' and class types that have been adorned with protocol
2281 // information (id<p>, C<p>*). The protocol references need to be rewritten!
John McCall183700f2009-09-21 23:43:11 +00002282 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002283 assert(funcType && "missing function type");
Douglas Gregor72564e72009-02-26 23:50:07 +00002284 proto = dyn_cast<FunctionProtoType>(funcType);
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002285 if (!proto)
2286 return;
2287 Type = proto->getResultType();
2288 }
Steve Naroff3d7e7862009-12-05 15:55:59 +00002289 else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2290 Loc = FD->getLocation();
2291 Type = FD->getType();
2292 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002293 else
2294 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002295
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002296 if (needToScanForQualifiers(Type)) {
Steve Naroffd5255f52007-11-01 13:24:47 +00002297 // Since types are unique, we need to scan the buffer.
Mike Stump1eb44332009-09-09 15:08:12 +00002298
Steve Naroffd5255f52007-11-01 13:24:47 +00002299 const char *endBuf = SM->getCharacterData(Loc);
2300 const char *startBuf = endBuf;
Steve Naroff6cafbf22008-05-31 05:02:17 +00002301 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
Steve Naroffd5255f52007-11-01 13:24:47 +00002302 startBuf--; // scan backward (from the decl location) for return type.
2303 const char *startRef = 0, *endRef = 0;
2304 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2305 // Get the locations of the startRef, endRef.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00002306 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-endBuf);
2307 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-endBuf+1);
Steve Naroffd5255f52007-11-01 13:24:47 +00002308 // Comment out the protocol references.
Benjamin Kramerd999b372010-02-14 14:14:16 +00002309 InsertText(LessLoc, "/*");
2310 InsertText(GreaterLoc, "*/");
Steve Naroff9165ad32007-10-31 04:38:33 +00002311 }
2312 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002313 if (!proto)
2314 return; // most likely, was a variable
Steve Naroffd5255f52007-11-01 13:24:47 +00002315 // Now check arguments.
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002316 const char *startBuf = SM->getCharacterData(Loc);
2317 const char *startFuncBuf = startBuf;
Steve Naroffd5255f52007-11-01 13:24:47 +00002318 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
2319 if (needToScanForQualifiers(proto->getArgType(i))) {
2320 // Since types are unique, we need to scan the buffer.
Mike Stump1eb44332009-09-09 15:08:12 +00002321
Steve Naroffd5255f52007-11-01 13:24:47 +00002322 const char *endBuf = startBuf;
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002323 // scan forward (from the decl location) for argument types.
2324 scanToNextArgument(endBuf);
Steve Naroffd5255f52007-11-01 13:24:47 +00002325 const char *startRef = 0, *endRef = 0;
2326 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2327 // Get the locations of the startRef, endRef.
Mike Stump1eb44332009-09-09 15:08:12 +00002328 SourceLocation LessLoc =
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00002329 Loc.getLocWithOffset(startRef-startFuncBuf);
Mike Stump1eb44332009-09-09 15:08:12 +00002330 SourceLocation GreaterLoc =
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00002331 Loc.getLocWithOffset(endRef-startFuncBuf+1);
Steve Naroffd5255f52007-11-01 13:24:47 +00002332 // Comment out the protocol references.
Benjamin Kramerd999b372010-02-14 14:14:16 +00002333 InsertText(LessLoc, "/*");
2334 InsertText(GreaterLoc, "*/");
Steve Naroffd5255f52007-11-01 13:24:47 +00002335 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002336 startBuf = ++endBuf;
2337 }
2338 else {
Steve Naroffaba49d12008-08-06 15:58:23 +00002339 // If the function name is derived from a macro expansion, then the
2340 // argument buffer will not follow the name. Need to speak with Chris.
2341 while (*startBuf && *startBuf != ')' && *startBuf != ',')
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002342 startBuf++; // scan forward (from the decl location) for argument types.
2343 startBuf++;
2344 }
Steve Naroffd5255f52007-11-01 13:24:47 +00002345 }
Steve Naroff9165ad32007-10-31 04:38:33 +00002346}
2347
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002348void RewriteObjC::RewriteTypeOfDecl(VarDecl *ND) {
2349 QualType QT = ND->getType();
2350 const Type* TypePtr = QT->getAs<Type>();
2351 if (!isa<TypeOfExprType>(TypePtr))
2352 return;
2353 while (isa<TypeOfExprType>(TypePtr)) {
2354 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
2355 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
2356 TypePtr = QT->getAs<Type>();
2357 }
2358 // FIXME. This will not work for multiple declarators; as in:
2359 // __typeof__(a) b,c,d;
Douglas Gregor30c42402011-09-27 22:38:19 +00002360 std::string TypeAsString(QT.getAsString(Context->getPrintingPolicy()));
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002361 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
2362 const char *startBuf = SM->getCharacterData(DeclLoc);
2363 if (ND->getInit()) {
2364 std::string Name(ND->getNameAsString());
2365 TypeAsString += " " + Name + " = ";
2366 Expr *E = ND->getInit();
2367 SourceLocation startLoc;
2368 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
2369 startLoc = ECE->getLParenLoc();
2370 else
2371 startLoc = E->getLocStart();
Chandler Carruth40278532011-07-25 16:49:02 +00002372 startLoc = SM->getExpansionLoc(startLoc);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002373 const char *endBuf = SM->getCharacterData(startLoc);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002374 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002375 }
2376 else {
2377 SourceLocation X = ND->getLocEnd();
Chandler Carruth40278532011-07-25 16:49:02 +00002378 X = SM->getExpansionLoc(X);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002379 const char *endBuf = SM->getCharacterData(X);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002380 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002381 }
2382}
2383
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002384// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
Steve Naroffb29b4272008-04-14 22:03:09 +00002385void RewriteObjC::SynthSelGetUidFunctionDecl() {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002386 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002387 SmallVector<QualType, 16> ArgTys;
John McCall0953e762009-09-24 19:53:00 +00002388 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
John McCalle23cf432010-12-14 08:05:40 +00002389 QualType getFuncType =
2390 getSimpleFunctionType(Context->getObjCSelType(), &ArgTys[0], ArgTys.size());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002391 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002392 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002393 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002394 SelGetUidIdent, getFuncType, 0,
John McCalld931b082010-08-26 03:08:43 +00002395 SC_Extern,
2396 SC_None, false);
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002397}
2398
Steve Naroffb29b4272008-04-14 22:03:09 +00002399void RewriteObjC::RewriteFunctionDecl(FunctionDecl *FD) {
Steve Naroff09b266e2007-10-30 23:14:51 +00002400 // declared in <objc/objc.h>
Douglas Gregor51efe562009-01-09 01:47:02 +00002401 if (FD->getIdentifier() &&
Daniel Dunbar4087f272010-08-17 22:39:59 +00002402 FD->getName() == "sel_registerName") {
Steve Naroff09b266e2007-10-30 23:14:51 +00002403 SelGetUidFunctionDecl = FD;
Steve Naroff9165ad32007-10-31 04:38:33 +00002404 return;
2405 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002406 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff09b266e2007-10-30 23:14:51 +00002407}
2408
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00002409void RewriteObjC::RewriteBlockPointerType(std::string& Str, QualType Type) {
Douglas Gregor30c42402011-09-27 22:38:19 +00002410 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
Fariborz Jahanian52b2e1e2010-02-12 17:52:31 +00002411 const char *argPtr = TypeString.c_str();
2412 if (!strchr(argPtr, '^')) {
2413 Str += TypeString;
2414 return;
2415 }
2416 while (*argPtr) {
2417 Str += (*argPtr == '^' ? '*' : *argPtr);
2418 argPtr++;
2419 }
2420}
2421
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00002422// FIXME. Consolidate this routine with RewriteBlockPointerType.
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00002423void RewriteObjC::RewriteBlockPointerTypeVariable(std::string& Str,
2424 ValueDecl *VD) {
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00002425 QualType Type = VD->getType();
Douglas Gregor30c42402011-09-27 22:38:19 +00002426 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00002427 const char *argPtr = TypeString.c_str();
2428 int paren = 0;
2429 while (*argPtr) {
2430 switch (*argPtr) {
2431 case '(':
2432 Str += *argPtr;
2433 paren++;
2434 break;
2435 case ')':
2436 Str += *argPtr;
2437 paren--;
2438 break;
2439 case '^':
2440 Str += '*';
2441 if (paren == 1)
2442 Str += VD->getNameAsString();
2443 break;
2444 default:
2445 Str += *argPtr;
2446 break;
2447 }
2448 argPtr++;
2449 }
2450}
2451
2452
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002453void RewriteObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) {
2454 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
2455 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2456 const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(funcType);
2457 if (!proto)
2458 return;
2459 QualType Type = proto->getResultType();
Douglas Gregor30c42402011-09-27 22:38:19 +00002460 std::string FdStr = Type.getAsString(Context->getPrintingPolicy());
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002461 FdStr += " ";
Daniel Dunbar4087f272010-08-17 22:39:59 +00002462 FdStr += FD->getName();
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002463 FdStr += "(";
2464 unsigned numArgs = proto->getNumArgs();
2465 for (unsigned i = 0; i < numArgs; i++) {
2466 QualType ArgType = proto->getArgType(i);
Fariborz Jahanian52b2e1e2010-02-12 17:52:31 +00002467 RewriteBlockPointerType(FdStr, ArgType);
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002468 if (i+1 < numArgs)
2469 FdStr += ", ";
2470 }
2471 FdStr += ");\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00002472 InsertText(FunLocStart, FdStr);
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002473 CurFunctionDeclToDeclareForBlock = 0;
2474}
2475
Steve Naroffc0a123c2008-03-11 17:37:02 +00002476// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
Steve Naroffb29b4272008-04-14 22:03:09 +00002477void RewriteObjC::SynthSuperContructorFunctionDecl() {
Steve Naroffc0a123c2008-03-11 17:37:02 +00002478 if (SuperContructorFunctionDecl)
2479 return;
Steve Naroff46a98a72008-12-23 20:11:22 +00002480 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002481 SmallVector<QualType, 16> ArgTys;
Steve Naroffc0a123c2008-03-11 17:37:02 +00002482 QualType argT = Context->getObjCIdType();
2483 assert(!argT.isNull() && "Can't find 'id' type");
2484 ArgTys.push_back(argT);
2485 ArgTys.push_back(argT);
John McCalle23cf432010-12-14 08:05:40 +00002486 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2487 &ArgTys[0], ArgTys.size());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002488 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002489 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002490 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002491 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002492 SC_Extern,
2493 SC_None, false);
Steve Naroffc0a123c2008-03-11 17:37:02 +00002494}
2495
Steve Naroff09b266e2007-10-30 23:14:51 +00002496// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002497void RewriteObjC::SynthMsgSendFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00002498 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002499 SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002500 QualType argT = Context->getObjCIdType();
Steve Naroff09b266e2007-10-30 23:14:51 +00002501 assert(!argT.isNull() && "Can't find 'id' type");
2502 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002503 argT = Context->getObjCSelType();
Steve Naroff09b266e2007-10-30 23:14:51 +00002504 assert(!argT.isNull() && "Can't find 'SEL' type");
2505 ArgTys.push_back(argT);
John McCalle23cf432010-12-14 08:05:40 +00002506 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2507 &ArgTys[0], ArgTys.size(),
2508 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002509 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002510 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002511 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002512 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002513 SC_Extern,
2514 SC_None, false);
Steve Naroff09b266e2007-10-30 23:14:51 +00002515}
2516
Steve Naroff874e2322007-11-15 10:28:18 +00002517// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002518void RewriteObjC::SynthMsgSendSuperFunctionDecl() {
Steve Naroff874e2322007-11-15 10:28:18 +00002519 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002520 SmallVector<QualType, 16> ArgTys;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002521 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00002522 SourceLocation(), SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002523 &Context->Idents.get("objc_super"));
Steve Naroff874e2322007-11-15 10:28:18 +00002524 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2525 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2526 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002527 argT = Context->getObjCSelType();
Steve Naroff874e2322007-11-15 10:28:18 +00002528 assert(!argT.isNull() && "Can't find 'SEL' type");
2529 ArgTys.push_back(argT);
John McCalle23cf432010-12-14 08:05:40 +00002530 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2531 &ArgTys[0], ArgTys.size(),
2532 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002533 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002534 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002535 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002536 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002537 SC_Extern,
2538 SC_None, false);
Steve Naroff874e2322007-11-15 10:28:18 +00002539}
2540
Fariborz Jahanian336c8f72011-10-11 23:02:37 +00002541// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002542void RewriteObjC::SynthMsgSendStretFunctionDecl() {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002543 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002544 SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002545 QualType argT = Context->getObjCIdType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002546 assert(!argT.isNull() && "Can't find 'id' type");
2547 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002548 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002549 assert(!argT.isNull() && "Can't find 'SEL' type");
2550 ArgTys.push_back(argT);
Fariborz Jahanian336c8f72011-10-11 23:02:37 +00002551 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
John McCalle23cf432010-12-14 08:05:40 +00002552 &ArgTys[0], ArgTys.size(),
2553 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002554 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002555 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002556 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002557 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002558 SC_Extern,
2559 SC_None, false);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002560}
2561
Mike Stump1eb44332009-09-09 15:08:12 +00002562// SynthMsgSendSuperStretFunctionDecl -
Fariborz Jahanian336c8f72011-10-11 23:02:37 +00002563// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002564void RewriteObjC::SynthMsgSendSuperStretFunctionDecl() {
Mike Stump1eb44332009-09-09 15:08:12 +00002565 IdentifierInfo *msgSendIdent =
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002566 &Context->Idents.get("objc_msgSendSuper_stret");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002567 SmallVector<QualType, 16> ArgTys;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002568 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00002569 SourceLocation(), SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002570 &Context->Idents.get("objc_super"));
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002571 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2572 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2573 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002574 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002575 assert(!argT.isNull() && "Can't find 'SEL' type");
2576 ArgTys.push_back(argT);
Fariborz Jahanian336c8f72011-10-11 23:02:37 +00002577 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
John McCalle23cf432010-12-14 08:05:40 +00002578 &ArgTys[0], ArgTys.size(),
2579 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002580 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002581 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002582 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002583 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002584 SC_Extern,
2585 SC_None, false);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002586}
2587
Steve Naroff1284db82008-05-08 22:02:18 +00002588// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002589void RewriteObjC::SynthMsgSendFpretFunctionDecl() {
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002590 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002591 SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002592 QualType argT = Context->getObjCIdType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002593 assert(!argT.isNull() && "Can't find 'id' type");
2594 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002595 argT = Context->getObjCSelType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002596 assert(!argT.isNull() && "Can't find 'SEL' type");
2597 ArgTys.push_back(argT);
John McCalle23cf432010-12-14 08:05:40 +00002598 QualType msgSendType = getSimpleFunctionType(Context->DoubleTy,
2599 &ArgTys[0], ArgTys.size(),
2600 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002601 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002602 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002603 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002604 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002605 SC_Extern,
2606 SC_None, false);
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002607}
2608
Steve Naroff09b266e2007-10-30 23:14:51 +00002609// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00002610void RewriteObjC::SynthGetClassFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00002611 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002612 SmallVector<QualType, 16> ArgTys;
John McCall0953e762009-09-24 19:53:00 +00002613 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
John McCalle23cf432010-12-14 08:05:40 +00002614 QualType getClassType = getSimpleFunctionType(Context->getObjCIdType(),
2615 &ArgTys[0], ArgTys.size());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002616 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002617 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002618 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002619 getClassIdent, getClassType, 0,
John McCalld931b082010-08-26 03:08:43 +00002620 SC_Extern,
2621 SC_None, false);
Steve Naroff09b266e2007-10-30 23:14:51 +00002622}
2623
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002624// SynthGetSuperClassFunctionDecl - Class class_getSuperclass(Class cls);
2625void RewriteObjC::SynthGetSuperClassFunctionDecl() {
2626 IdentifierInfo *getSuperClassIdent =
2627 &Context->Idents.get("class_getSuperclass");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002628 SmallVector<QualType, 16> ArgTys;
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002629 ArgTys.push_back(Context->getObjCClassType());
John McCalle23cf432010-12-14 08:05:40 +00002630 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
2631 &ArgTys[0], ArgTys.size());
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002632 GetSuperClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Douglas Gregor16573fa2010-04-19 22:54:31 +00002633 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002634 SourceLocation(),
Douglas Gregor16573fa2010-04-19 22:54:31 +00002635 getSuperClassIdent,
2636 getClassType, 0,
John McCalld931b082010-08-26 03:08:43 +00002637 SC_Extern,
2638 SC_None,
Douglas Gregor16573fa2010-04-19 22:54:31 +00002639 false);
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002640}
2641
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002642// SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00002643void RewriteObjC::SynthGetMetaClassFunctionDecl() {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002644 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002645 SmallVector<QualType, 16> ArgTys;
John McCall0953e762009-09-24 19:53:00 +00002646 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
John McCalle23cf432010-12-14 08:05:40 +00002647 QualType getClassType = getSimpleFunctionType(Context->getObjCIdType(),
2648 &ArgTys[0], ArgTys.size());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002649 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002650 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002651 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002652 getClassIdent, getClassType, 0,
John McCalld931b082010-08-26 03:08:43 +00002653 SC_Extern,
2654 SC_None, false);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002655}
2656
Steve Naroffb29b4272008-04-14 22:03:09 +00002657Stmt *RewriteObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002658 QualType strType = getConstantStringStructType();
2659
2660 std::string S = "__NSConstantStringImpl_";
Steve Naroff7691d9b2008-05-31 03:35:42 +00002661
2662 std::string tmpName = InFileName;
2663 unsigned i;
2664 for (i=0; i < tmpName.length(); i++) {
2665 char c = tmpName.at(i);
2666 // replace any non alphanumeric characters with '_'.
2667 if (!isalpha(c) && (c < '0' || c > '9'))
2668 tmpName[i] = '_';
2669 }
2670 S += tmpName;
2671 S += "_";
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002672 S += utostr(NumObjCStringLiterals++);
2673
Steve Naroffba92b2e2008-03-27 22:29:16 +00002674 Preamble += "static __NSConstantStringImpl " + S;
2675 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2676 Preamble += "0x000007c8,"; // utf8_str
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002677 // The pretty printer for StringLiteral handles escape characters properly.
Ted Kremeneka95d3752008-09-13 05:16:45 +00002678 std::string prettyBufS;
2679 llvm::raw_string_ostream prettyBuf(prettyBufS);
Chris Lattnere4f21422009-06-30 01:26:17 +00002680 Exp->getString()->printPretty(prettyBuf, *Context, 0,
2681 PrintingPolicy(LangOpts));
Steve Naroffba92b2e2008-03-27 22:29:16 +00002682 Preamble += prettyBuf.str();
2683 Preamble += ",";
Steve Narofffd5b76f2009-12-06 01:48:44 +00002684 Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00002685
2686 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002687 SourceLocation(), &Context->Idents.get(S),
2688 strType, 0, SC_Static, SC_None);
John McCallf89e55a2010-11-18 06:31:45 +00002689 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, strType, VK_LValue,
2690 SourceLocation());
John McCall2de56d12010-08-25 11:45:40 +00002691 Expr *Unop = new (Context) UnaryOperator(DRE, UO_AddrOf,
Mike Stump1eb44332009-09-09 15:08:12 +00002692 Context->getPointerType(DRE->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00002693 VK_RValue, OK_Ordinary,
2694 SourceLocation());
Steve Naroff96984642007-11-08 14:30:50 +00002695 // cast to NSConstantString *
John McCall9d125032010-01-15 18:39:57 +00002696 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(),
John McCall1d9b3b22011-09-09 05:25:32 +00002697 CK_CPointerToObjCPointerCast, Unop);
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002698 ReplaceStmt(Exp, cast);
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00002699 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroff96984642007-11-08 14:30:50 +00002700 return cast;
Steve Naroffbeaf2992007-11-03 11:27:19 +00002701}
2702
Steve Naroff874e2322007-11-15 10:28:18 +00002703// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
Steve Naroffb29b4272008-04-14 22:03:09 +00002704QualType RewriteObjC::getSuperStructType() {
Steve Naroff874e2322007-11-15 10:28:18 +00002705 if (!SuperStructDecl) {
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002706 SuperStructDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00002707 SourceLocation(), SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002708 &Context->Idents.get("objc_super"));
Steve Naroff874e2322007-11-15 10:28:18 +00002709 QualType FieldTypes[2];
Mike Stump1eb44332009-09-09 15:08:12 +00002710
Steve Naroff874e2322007-11-15 10:28:18 +00002711 // struct objc_object *receiver;
Mike Stump1eb44332009-09-09 15:08:12 +00002712 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff874e2322007-11-15 10:28:18 +00002713 // struct objc_class *super;
Mike Stump1eb44332009-09-09 15:08:12 +00002714 FieldTypes[1] = Context->getObjCClassType();
Douglas Gregor44b43212008-12-11 16:49:14 +00002715
Steve Naroff874e2322007-11-15 10:28:18 +00002716 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00002717 for (unsigned i = 0; i < 2; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00002718 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002719 SourceLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00002720 SourceLocation(), 0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002721 FieldTypes[i], 0,
2722 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00002723 /*Mutable=*/false,
2724 /*HasInit=*/false));
Douglas Gregor44b43212008-12-11 16:49:14 +00002725 }
Mike Stump1eb44332009-09-09 15:08:12 +00002726
Douglas Gregor838db382010-02-11 01:19:42 +00002727 SuperStructDecl->completeDefinition();
Steve Naroff874e2322007-11-15 10:28:18 +00002728 }
2729 return Context->getTagDeclType(SuperStructDecl);
2730}
2731
Steve Naroffb29b4272008-04-14 22:03:09 +00002732QualType RewriteObjC::getConstantStringStructType() {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002733 if (!ConstantStringDecl) {
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002734 ConstantStringDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00002735 SourceLocation(), SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002736 &Context->Idents.get("__NSConstantStringImpl"));
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002737 QualType FieldTypes[4];
Mike Stump1eb44332009-09-09 15:08:12 +00002738
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002739 // struct objc_object *receiver;
Mike Stump1eb44332009-09-09 15:08:12 +00002740 FieldTypes[0] = Context->getObjCIdType();
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002741 // int flags;
Mike Stump1eb44332009-09-09 15:08:12 +00002742 FieldTypes[1] = Context->IntTy;
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002743 // char *str;
Mike Stump1eb44332009-09-09 15:08:12 +00002744 FieldTypes[2] = Context->getPointerType(Context->CharTy);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002745 // long length;
Mike Stump1eb44332009-09-09 15:08:12 +00002746 FieldTypes[3] = Context->LongTy;
Douglas Gregor44b43212008-12-11 16:49:14 +00002747
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002748 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00002749 for (unsigned i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00002750 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
2751 ConstantStringDecl,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002752 SourceLocation(),
Douglas Gregor44b43212008-12-11 16:49:14 +00002753 SourceLocation(), 0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002754 FieldTypes[i], 0,
Douglas Gregor44b43212008-12-11 16:49:14 +00002755 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00002756 /*Mutable=*/true,
2757 /*HasInit=*/false));
Douglas Gregor44b43212008-12-11 16:49:14 +00002758 }
2759
Douglas Gregor838db382010-02-11 01:19:42 +00002760 ConstantStringDecl->completeDefinition();
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002761 }
2762 return Context->getTagDeclType(ConstantStringDecl);
2763}
2764
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002765Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp,
2766 SourceLocation StartLoc,
2767 SourceLocation EndLoc) {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002768 if (!SelGetUidFunctionDecl)
2769 SynthSelGetUidFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00002770 if (!MsgSendFunctionDecl)
2771 SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +00002772 if (!MsgSendSuperFunctionDecl)
2773 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002774 if (!MsgSendStretFunctionDecl)
2775 SynthMsgSendStretFunctionDecl();
2776 if (!MsgSendSuperStretFunctionDecl)
2777 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002778 if (!MsgSendFpretFunctionDecl)
2779 SynthMsgSendFpretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00002780 if (!GetClassFunctionDecl)
2781 SynthGetClassFunctionDecl();
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002782 if (!GetSuperClassFunctionDecl)
2783 SynthGetSuperClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002784 if (!GetMetaClassFunctionDecl)
2785 SynthGetMetaClassFunctionDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00002786
Steve Naroff874e2322007-11-15 10:28:18 +00002787 // default to objc_msgSend().
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002788 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2789 // May need to use objc_msgSend_stret() as well.
2790 FunctionDecl *MsgSendStretFlavor = 0;
Steve Naroff621edce2009-04-29 16:37:50 +00002791 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
2792 QualType resultType = mDecl->getResultType();
Douglas Gregorfb87b892010-04-26 21:31:17 +00002793 if (resultType->isRecordType())
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002794 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Chris Lattner8b51fd72008-07-26 22:36:27 +00002795 else if (resultType->isRealFloatingType())
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002796 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002797 }
Mike Stump1eb44332009-09-09 15:08:12 +00002798
Steve Naroff934f2762007-10-24 22:48:43 +00002799 // Synthesize a call to objc_msgSend().
Chris Lattner5f9e2722011-07-23 10:55:15 +00002800 SmallVector<Expr*, 8> MsgExprs;
Douglas Gregor04badcf2010-04-21 00:45:42 +00002801 switch (Exp->getReceiverKind()) {
2802 case ObjCMessageExpr::SuperClass: {
2803 MsgSendFlavor = MsgSendSuperFunctionDecl;
2804 if (MsgSendStretFlavor)
2805 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2806 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
Mike Stump1eb44332009-09-09 15:08:12 +00002807
Douglas Gregor04badcf2010-04-21 00:45:42 +00002808 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
Mike Stump1eb44332009-09-09 15:08:12 +00002809
Chris Lattner5f9e2722011-07-23 10:55:15 +00002810 SmallVector<Expr*, 4> InitExprs;
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002811
Douglas Gregor04badcf2010-04-21 00:45:42 +00002812 // set the receiver to self, the first argument to all methods.
2813 InitExprs.push_back(
2814 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCalla5bbc502010-11-15 09:46:46 +00002815 CK_BitCast,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002816 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCallf89e55a2010-11-18 06:31:45 +00002817 Context->getObjCIdType(),
2818 VK_RValue,
2819 SourceLocation()))
Douglas Gregor04badcf2010-04-21 00:45:42 +00002820 ); // set the 'receiver'.
Mike Stump1eb44332009-09-09 15:08:12 +00002821
Douglas Gregor04badcf2010-04-21 00:45:42 +00002822 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
Chris Lattner5f9e2722011-07-23 10:55:15 +00002823 SmallVector<Expr*, 8> ClsExprs;
Douglas Gregor04badcf2010-04-21 00:45:42 +00002824 QualType argType = Context->getPointerType(Context->CharTy);
2825 ClsExprs.push_back(StringLiteral::Create(*Context,
Jay Foad65aa6882011-06-21 15:13:30 +00002826 ClassDecl->getIdentifier()->getName(),
Douglas Gregor5cee1192011-07-27 05:40:30 +00002827 StringLiteral::Ascii, false,
2828 argType, SourceLocation()));
Douglas Gregor04badcf2010-04-21 00:45:42 +00002829 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
2830 &ClsExprs[0],
2831 ClsExprs.size(),
2832 StartLoc,
2833 EndLoc);
2834 // (Class)objc_getClass("CurrentClass")
2835 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2836 Context->getObjCClassType(),
John McCall1d9b3b22011-09-09 05:25:32 +00002837 CK_CPointerToObjCPointerCast, Cls);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002838 ClsExprs.clear();
2839 ClsExprs.push_back(ArgExpr);
2840 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
2841 &ClsExprs[0], ClsExprs.size(),
2842 StartLoc, EndLoc);
2843
2844 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2845 // To turn off a warning, type-cast to 'id'
2846 InitExprs.push_back( // set 'super class', using class_getSuperclass().
2847 NoTypeInfoCStyleCastExpr(Context,
2848 Context->getObjCIdType(),
John McCalla5bbc502010-11-15 09:46:46 +00002849 CK_BitCast, Cls));
Douglas Gregor04badcf2010-04-21 00:45:42 +00002850 // struct objc_super
2851 QualType superType = getSuperStructType();
2852 Expr *SuperRep;
Steve Naroff621edce2009-04-29 16:37:50 +00002853
Francois Pichet62ec1f22011-09-17 17:15:52 +00002854 if (LangOpts.MicrosoftExt) {
Douglas Gregor04badcf2010-04-21 00:45:42 +00002855 SynthSuperContructorFunctionDecl();
2856 // Simulate a contructor call...
2857 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
John McCallf89e55a2010-11-18 06:31:45 +00002858 superType, VK_LValue,
2859 SourceLocation());
Douglas Gregor04badcf2010-04-21 00:45:42 +00002860 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
2861 InitExprs.size(),
John McCallf89e55a2010-11-18 06:31:45 +00002862 superType, VK_LValue,
2863 SourceLocation());
Douglas Gregor04badcf2010-04-21 00:45:42 +00002864 // The code for super is a little tricky to prevent collision with
2865 // the structure definition in the header. The rewriter has it's own
2866 // internal definition (__rw_objc_super) that is uses. This is why
2867 // we need the cast below. For example:
2868 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2869 //
John McCall2de56d12010-08-25 11:45:40 +00002870 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002871 Context->getPointerType(SuperRep->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00002872 VK_RValue, OK_Ordinary,
2873 SourceLocation());
Douglas Gregor04badcf2010-04-21 00:45:42 +00002874 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2875 Context->getPointerType(superType),
John McCalla5bbc502010-11-15 09:46:46 +00002876 CK_BitCast, SuperRep);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002877 } else {
Douglas Gregor04badcf2010-04-21 00:45:42 +00002878 // (struct objc_super) { <exprs from above> }
2879 InitListExpr *ILE =
2880 new (Context) InitListExpr(*Context, SourceLocation(),
2881 &InitExprs[0], InitExprs.size(),
2882 SourceLocation());
2883 TypeSourceInfo *superTInfo
2884 = Context->getTrivialTypeSourceInfo(superType);
2885 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
John McCallf89e55a2010-11-18 06:31:45 +00002886 superType, VK_LValue,
2887 ILE, false);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002888 // struct objc_super *
John McCall2de56d12010-08-25 11:45:40 +00002889 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002890 Context->getPointerType(SuperRep->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00002891 VK_RValue, OK_Ordinary,
2892 SourceLocation());
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002893 }
Douglas Gregor04badcf2010-04-21 00:45:42 +00002894 MsgExprs.push_back(SuperRep);
2895 break;
Steve Naroff6568d4d2007-11-14 23:54:14 +00002896 }
Douglas Gregor04badcf2010-04-21 00:45:42 +00002897
2898 case ObjCMessageExpr::Class: {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002899 SmallVector<Expr*, 8> ClsExprs;
Douglas Gregor04badcf2010-04-21 00:45:42 +00002900 QualType argType = Context->getPointerType(Context->CharTy);
2901 ObjCInterfaceDecl *Class
John McCall506b57e2010-05-17 21:00:27 +00002902 = Exp->getClassReceiver()->getAs<ObjCObjectType>()->getInterface();
Douglas Gregor04badcf2010-04-21 00:45:42 +00002903 IdentifierInfo *clsName = Class->getIdentifier();
2904 ClsExprs.push_back(StringLiteral::Create(*Context,
Jay Foad65aa6882011-06-21 15:13:30 +00002905 clsName->getName(),
Douglas Gregor5cee1192011-07-27 05:40:30 +00002906 StringLiteral::Ascii, false,
Anders Carlsson3e2193c2011-04-14 00:40:03 +00002907 argType, SourceLocation()));
Douglas Gregor04badcf2010-04-21 00:45:42 +00002908 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2909 &ClsExprs[0],
2910 ClsExprs.size(),
2911 StartLoc, EndLoc);
2912 MsgExprs.push_back(Cls);
2913 break;
2914 }
2915
2916 case ObjCMessageExpr::SuperInstance:{
2917 MsgSendFlavor = MsgSendSuperFunctionDecl;
2918 if (MsgSendStretFlavor)
2919 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2920 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2921 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
Chris Lattner5f9e2722011-07-23 10:55:15 +00002922 SmallVector<Expr*, 4> InitExprs;
Douglas Gregor04badcf2010-04-21 00:45:42 +00002923
2924 InitExprs.push_back(
2925 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCalla5bbc502010-11-15 09:46:46 +00002926 CK_BitCast,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002927 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCallf89e55a2010-11-18 06:31:45 +00002928 Context->getObjCIdType(),
2929 VK_RValue, SourceLocation()))
Douglas Gregor04badcf2010-04-21 00:45:42 +00002930 ); // set the 'receiver'.
2931
2932 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
Chris Lattner5f9e2722011-07-23 10:55:15 +00002933 SmallVector<Expr*, 8> ClsExprs;
Douglas Gregor04badcf2010-04-21 00:45:42 +00002934 QualType argType = Context->getPointerType(Context->CharTy);
2935 ClsExprs.push_back(StringLiteral::Create(*Context,
Jay Foad65aa6882011-06-21 15:13:30 +00002936 ClassDecl->getIdentifier()->getName(),
Douglas Gregor5cee1192011-07-27 05:40:30 +00002937 StringLiteral::Ascii, false, argType,
2938 SourceLocation()));
Douglas Gregor04badcf2010-04-21 00:45:42 +00002939 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2940 &ClsExprs[0],
2941 ClsExprs.size(),
2942 StartLoc, EndLoc);
2943 // (Class)objc_getClass("CurrentClass")
2944 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2945 Context->getObjCClassType(),
John McCalla5bbc502010-11-15 09:46:46 +00002946 CK_BitCast, Cls);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002947 ClsExprs.clear();
2948 ClsExprs.push_back(ArgExpr);
2949 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
2950 &ClsExprs[0], ClsExprs.size(),
2951 StartLoc, EndLoc);
2952
2953 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2954 // To turn off a warning, type-cast to 'id'
2955 InitExprs.push_back(
2956 // set 'super class', using class_getSuperclass().
2957 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCalla5bbc502010-11-15 09:46:46 +00002958 CK_BitCast, Cls));
Douglas Gregor04badcf2010-04-21 00:45:42 +00002959 // struct objc_super
2960 QualType superType = getSuperStructType();
2961 Expr *SuperRep;
2962
Francois Pichet62ec1f22011-09-17 17:15:52 +00002963 if (LangOpts.MicrosoftExt) {
Douglas Gregor04badcf2010-04-21 00:45:42 +00002964 SynthSuperContructorFunctionDecl();
2965 // Simulate a contructor call...
2966 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
John McCallf89e55a2010-11-18 06:31:45 +00002967 superType, VK_LValue,
2968 SourceLocation());
Douglas Gregor04badcf2010-04-21 00:45:42 +00002969 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
2970 InitExprs.size(),
John McCallf89e55a2010-11-18 06:31:45 +00002971 superType, VK_LValue, SourceLocation());
Douglas Gregor04badcf2010-04-21 00:45:42 +00002972 // The code for super is a little tricky to prevent collision with
2973 // the structure definition in the header. The rewriter has it's own
2974 // internal definition (__rw_objc_super) that is uses. This is why
2975 // we need the cast below. For example:
2976 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2977 //
John McCall2de56d12010-08-25 11:45:40 +00002978 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002979 Context->getPointerType(SuperRep->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00002980 VK_RValue, OK_Ordinary,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002981 SourceLocation());
2982 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2983 Context->getPointerType(superType),
John McCalla5bbc502010-11-15 09:46:46 +00002984 CK_BitCast, SuperRep);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002985 } else {
2986 // (struct objc_super) { <exprs from above> }
2987 InitListExpr *ILE =
2988 new (Context) InitListExpr(*Context, SourceLocation(),
2989 &InitExprs[0], InitExprs.size(),
2990 SourceLocation());
2991 TypeSourceInfo *superTInfo
2992 = Context->getTrivialTypeSourceInfo(superType);
2993 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
John McCallf89e55a2010-11-18 06:31:45 +00002994 superType, VK_RValue, ILE,
2995 false);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002996 }
2997 MsgExprs.push_back(SuperRep);
2998 break;
2999 }
3000
3001 case ObjCMessageExpr::Instance: {
3002 // Remove all type-casts because it may contain objc-style types; e.g.
3003 // Foo<Proto> *.
3004 Expr *recExpr = Exp->getInstanceReceiver();
3005 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
3006 recExpr = CE->getSubExpr();
Fariborz Jahanianbaac1ea2011-10-07 17:17:45 +00003007 CastKind CK = recExpr->getType()->isObjCObjectPointerType()
3008 ? CK_BitCast : recExpr->getType()->isBlockPointerType()
3009 ? CK_BlockPointerToObjCPointerCast
3010 : CK_CPointerToObjCPointerCast;
3011
Douglas Gregor04badcf2010-04-21 00:45:42 +00003012 recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
Fariborz Jahanianbaac1ea2011-10-07 17:17:45 +00003013 CK, recExpr);
Douglas Gregor04badcf2010-04-21 00:45:42 +00003014 MsgExprs.push_back(recExpr);
3015 break;
3016 }
3017 }
3018
Steve Naroffbeaf2992007-11-03 11:27:19 +00003019 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003020 SmallVector<Expr*, 8> SelExprs;
Steve Naroff934f2762007-10-24 22:48:43 +00003021 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump1eb44332009-09-09 15:08:12 +00003022 SelExprs.push_back(StringLiteral::Create(*Context,
Jay Foad65aa6882011-06-21 15:13:30 +00003023 Exp->getSelector().getAsString(),
Douglas Gregor5cee1192011-07-27 05:40:30 +00003024 StringLiteral::Ascii, false,
3025 argType, SourceLocation()));
Steve Naroff934f2762007-10-24 22:48:43 +00003026 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00003027 &SelExprs[0], SelExprs.size(),
3028 StartLoc,
3029 EndLoc);
Steve Naroff934f2762007-10-24 22:48:43 +00003030 MsgExprs.push_back(SelExp);
Mike Stump1eb44332009-09-09 15:08:12 +00003031
Steve Naroff934f2762007-10-24 22:48:43 +00003032 // Now push any user supplied arguments.
3033 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroff6568d4d2007-11-14 23:54:14 +00003034 Expr *userExpr = Exp->getArg(i);
Steve Naroff7e3411b2007-11-15 02:58:25 +00003035 // Make all implicit casts explicit...ICE comes in handy:-)
3036 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
3037 // Reuse the ICE type, it is exactly what the doctor ordered.
Fariborz Jahaniandff3f012011-02-26 01:31:36 +00003038 QualType type = ICE->getType();
3039 if (needToScanForQualifiers(type))
3040 type = Context->getObjCIdType();
Fariborz Jahanian1f906222010-05-25 15:56:08 +00003041 // Make sure we convert "type (^)(...)" to "type (*)(...)".
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00003042 (void)convertBlockPointerToFunctionPointer(type);
Fariborz Jahanian1a38b462011-08-04 23:58:03 +00003043 const Expr *SubExpr = ICE->IgnoreParenImpCasts();
John McCall1d9b3b22011-09-09 05:25:32 +00003044 CastKind CK;
3045 if (SubExpr->getType()->isIntegralType(*Context) &&
3046 type->isBooleanType()) {
3047 CK = CK_IntegralToBoolean;
3048 } else if (type->isObjCObjectPointerType()) {
3049 if (SubExpr->getType()->isBlockPointerType()) {
3050 CK = CK_BlockPointerToObjCPointerCast;
3051 } else if (SubExpr->getType()->isPointerType()) {
3052 CK = CK_CPointerToObjCPointerCast;
3053 } else {
3054 CK = CK_BitCast;
3055 }
3056 } else {
3057 CK = CK_BitCast;
3058 }
3059
3060 userExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, userExpr);
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00003061 }
3062 // Make id<P...> cast into an 'id' cast.
Douglas Gregor6eec8e82008-10-28 15:36:24 +00003063 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003064 if (CE->getType()->isObjCQualifiedIdType()) {
Douglas Gregor6eec8e82008-10-28 15:36:24 +00003065 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00003066 userExpr = CE->getSubExpr();
John McCall1d9b3b22011-09-09 05:25:32 +00003067 CastKind CK;
3068 if (userExpr->getType()->isIntegralType(*Context)) {
3069 CK = CK_IntegralToPointer;
3070 } else if (userExpr->getType()->isBlockPointerType()) {
3071 CK = CK_BlockPointerToObjCPointerCast;
3072 } else if (userExpr->getType()->isPointerType()) {
3073 CK = CK_CPointerToObjCPointerCast;
3074 } else {
3075 CK = CK_BitCast;
3076 }
John McCall9d125032010-01-15 18:39:57 +00003077 userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCall1d9b3b22011-09-09 05:25:32 +00003078 CK, userExpr);
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00003079 }
Mike Stump1eb44332009-09-09 15:08:12 +00003080 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00003081 MsgExprs.push_back(userExpr);
Steve Naroff621edce2009-04-29 16:37:50 +00003082 // We've transferred the ownership to MsgExprs. For now, we *don't* null
3083 // out the argument in the original expression (since we aren't deleting
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003084 // the ObjCMessageExpr). See RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroff621edce2009-04-29 16:37:50 +00003085 //Exp->setArg(i, 0);
Steve Naroff934f2762007-10-24 22:48:43 +00003086 }
Steve Naroffab972d32007-11-04 22:37:50 +00003087 // Generate the funky cast.
3088 CastExpr *cast;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003089 SmallVector<QualType, 8> ArgTypes;
Steve Naroffab972d32007-11-04 22:37:50 +00003090 QualType returnType;
Mike Stump1eb44332009-09-09 15:08:12 +00003091
Steve Naroffab972d32007-11-04 22:37:50 +00003092 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroffc3a438c2007-11-15 10:43:57 +00003093 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
3094 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
3095 else
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003096 ArgTypes.push_back(Context->getObjCIdType());
3097 ArgTypes.push_back(Context->getObjCSelType());
Chris Lattner89951a82009-02-20 18:43:26 +00003098 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
Steve Naroffab972d32007-11-04 22:37:50 +00003099 // Push any user argument types.
Chris Lattner89951a82009-02-20 18:43:26 +00003100 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
3101 E = OMD->param_end(); PI != E; ++PI) {
3102 QualType t = (*PI)->getType()->isObjCQualifiedIdType()
Mike Stump1eb44332009-09-09 15:08:12 +00003103 ? Context->getObjCIdType()
Chris Lattner89951a82009-02-20 18:43:26 +00003104 : (*PI)->getType();
Steve Naroffa206b062008-10-29 14:49:46 +00003105 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00003106 (void)convertBlockPointerToFunctionPointer(t);
Steve Naroff352336b2007-11-05 14:36:37 +00003107 ArgTypes.push_back(t);
3108 }
Fariborz Jahanian3a448fb2011-09-10 17:01:56 +00003109 returnType = Exp->getType();
3110 convertToUnqualifiedObjCType(returnType);
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00003111 (void)convertBlockPointerToFunctionPointer(returnType);
Steve Naroffab972d32007-11-04 22:37:50 +00003112 } else {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003113 returnType = Context->getObjCIdType();
Steve Naroffab972d32007-11-04 22:37:50 +00003114 }
3115 // Get the type, we will need to reference it in a couple spots.
Steve Naroff874e2322007-11-15 10:28:18 +00003116 QualType msgSendType = MsgSendFlavor->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00003117
Steve Naroffab972d32007-11-04 22:37:50 +00003118 // Create a reference to the objc_msgSend() declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00003119 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, msgSendType,
John McCallf89e55a2010-11-18 06:31:45 +00003120 VK_LValue, SourceLocation());
Steve Naroffab972d32007-11-04 22:37:50 +00003121
Mike Stump1eb44332009-09-09 15:08:12 +00003122 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
Steve Naroffab972d32007-11-04 22:37:50 +00003123 // If we don't do this cast, we get the following bizarre warning/note:
3124 // xx.m:13: warning: function called through a non-compatible type
3125 // xx.m:13: note: if this code is reached, the program will abort
John McCall9d125032010-01-15 18:39:57 +00003126 cast = NoTypeInfoCStyleCastExpr(Context,
3127 Context->getPointerType(Context->VoidTy),
John McCalla5bbc502010-11-15 09:46:46 +00003128 CK_BitCast, DRE);
Mike Stump1eb44332009-09-09 15:08:12 +00003129
Steve Naroffab972d32007-11-04 22:37:50 +00003130 // Now do the "normal" pointer to function cast.
John McCalle23cf432010-12-14 08:05:40 +00003131 QualType castType =
3132 getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
3133 // If we don't have a method decl, force a variadic cast.
3134 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true);
Steve Naroffab972d32007-11-04 22:37:50 +00003135 castType = Context->getPointerType(castType);
John McCalla5bbc502010-11-15 09:46:46 +00003136 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00003137 cast);
Steve Naroffab972d32007-11-04 22:37:50 +00003138
3139 // Don't forget the parens to enforce the proper binding.
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00003140 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
Mike Stump1eb44332009-09-09 15:08:12 +00003141
John McCall183700f2009-09-21 23:43:11 +00003142 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Ted Kremenek668bf912009-02-09 20:51:47 +00003143 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
Mike Stump1eb44332009-09-09 15:08:12 +00003144 MsgExprs.size(),
John McCallf89e55a2010-11-18 06:31:45 +00003145 FT->getResultType(), VK_RValue,
3146 EndLoc);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00003147 Stmt *ReplacingStmt = CE;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003148 if (MsgSendStretFlavor) {
3149 // We have the method which returns a struct/union. Must also generate
3150 // call to objc_msgSend_stret and hang both varieties on a conditional
3151 // expression which dictate which one to envoke depending on size of
3152 // method's return type.
Mike Stump1eb44332009-09-09 15:08:12 +00003153
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003154 // Create a reference to the objc_msgSend_stret() declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00003155 DeclRefExpr *STDRE = new (Context) DeclRefExpr(MsgSendStretFlavor, msgSendType,
John McCallf89e55a2010-11-18 06:31:45 +00003156 VK_LValue, SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003157 // Need to cast objc_msgSend_stret to "void *" (see above comment).
John McCall9d125032010-01-15 18:39:57 +00003158 cast = NoTypeInfoCStyleCastExpr(Context,
3159 Context->getPointerType(Context->VoidTy),
John McCalla5bbc502010-11-15 09:46:46 +00003160 CK_BitCast, STDRE);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003161 // Now do the "normal" pointer to function cast.
John McCalle23cf432010-12-14 08:05:40 +00003162 castType = getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
3163 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003164 castType = Context->getPointerType(castType);
John McCalla5bbc502010-11-15 09:46:46 +00003165 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00003166 cast);
Mike Stump1eb44332009-09-09 15:08:12 +00003167
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003168 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00003169 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
Mike Stump1eb44332009-09-09 15:08:12 +00003170
John McCall183700f2009-09-21 23:43:11 +00003171 FT = msgSendType->getAs<FunctionType>();
Ted Kremenek668bf912009-02-09 20:51:47 +00003172 CallExpr *STCE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
Mike Stump1eb44332009-09-09 15:08:12 +00003173 MsgExprs.size(),
John McCallf89e55a2010-11-18 06:31:45 +00003174 FT->getResultType(), VK_RValue,
3175 SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00003176
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003177 // Build sizeof(returnType)
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003178 UnaryExprOrTypeTraitExpr *sizeofExpr =
3179 new (Context) UnaryExprOrTypeTraitExpr(UETT_SizeOf,
3180 Context->getTrivialTypeSourceInfo(returnType),
3181 Context->getSizeType(), SourceLocation(),
3182 SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003183 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
3184 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
3185 // For X86 it is more complicated and some kind of target specific routine
3186 // is needed to decide what to do.
Mike Stump1eb44332009-09-09 15:08:12 +00003187 unsigned IntSize =
Chris Lattner98be4942008-03-05 18:54:05 +00003188 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00003189 IntegerLiteral *limit = IntegerLiteral::Create(*Context,
3190 llvm::APInt(IntSize, 8),
3191 Context->IntTy,
3192 SourceLocation());
John McCallf89e55a2010-11-18 06:31:45 +00003193 BinaryOperator *lessThanExpr =
3194 new (Context) BinaryOperator(sizeofExpr, limit, BO_LE, Context->IntTy,
3195 VK_RValue, OK_Ordinary, SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003196 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
Mike Stump1eb44332009-09-09 15:08:12 +00003197 ConditionalOperator *CondExpr =
Douglas Gregor47e1f7c2009-08-26 14:37:04 +00003198 new (Context) ConditionalOperator(lessThanExpr,
3199 SourceLocation(), CE,
John McCall56ca35d2011-02-17 10:25:35 +00003200 SourceLocation(), STCE,
John McCall09431682010-11-18 19:01:18 +00003201 returnType, VK_RValue, OK_Ordinary);
Fariborz Jahanianf9b949f2010-08-31 18:02:20 +00003202 ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3203 CondExpr);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003204 }
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003205 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00003206 return ReplacingStmt;
3207}
3208
Steve Naroffb29b4272008-04-14 22:03:09 +00003209Stmt *RewriteObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00003210 Stmt *ReplacingStmt = SynthMessageExpr(Exp, Exp->getLocStart(),
3211 Exp->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +00003212
Steve Naroff934f2762007-10-24 22:48:43 +00003213 // Now do the actual rewrite.
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00003214 ReplaceStmt(Exp, ReplacingStmt);
Mike Stump1eb44332009-09-09 15:08:12 +00003215
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003216 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00003217 return ReplacingStmt;
Steve Naroffebf2b562007-10-23 23:50:29 +00003218}
3219
Steve Naroff621edce2009-04-29 16:37:50 +00003220// typedef struct objc_object Protocol;
3221QualType RewriteObjC::getProtocolType() {
3222 if (!ProtocolTypeDecl) {
John McCalla93c9342009-12-07 02:54:59 +00003223 TypeSourceInfo *TInfo
3224 = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
Steve Naroff621edce2009-04-29 16:37:50 +00003225 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
Abramo Bagnara344577e2011-03-06 15:48:19 +00003226 SourceLocation(), SourceLocation(),
Steve Naroff621edce2009-04-29 16:37:50 +00003227 &Context->Idents.get("Protocol"),
John McCalla93c9342009-12-07 02:54:59 +00003228 TInfo);
Steve Naroff621edce2009-04-29 16:37:50 +00003229 }
3230 return Context->getTypeDeclType(ProtocolTypeDecl);
3231}
3232
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00003233/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
Steve Naroff621edce2009-04-29 16:37:50 +00003234/// a synthesized/forward data reference (to the protocol's metadata).
3235/// The forward references (and metadata) are generated in
3236/// RewriteObjC::HandleTranslationUnit().
Steve Naroffb29b4272008-04-14 22:03:09 +00003237Stmt *RewriteObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Steve Naroff621edce2009-04-29 16:37:50 +00003238 std::string Name = "_OBJC_PROTOCOL_" + Exp->getProtocol()->getNameAsString();
3239 IdentifierInfo *ID = &Context->Idents.get(Name);
Mike Stump1eb44332009-09-09 15:08:12 +00003240 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003241 SourceLocation(), ID, getProtocolType(), 0,
John McCalld931b082010-08-26 03:08:43 +00003242 SC_Extern, SC_None);
John McCallf89e55a2010-11-18 06:31:45 +00003243 DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, getProtocolType(), VK_LValue,
3244 SourceLocation());
John McCall2de56d12010-08-25 11:45:40 +00003245 Expr *DerefExpr = new (Context) UnaryOperator(DRE, UO_AddrOf,
Steve Naroff621edce2009-04-29 16:37:50 +00003246 Context->getPointerType(DRE->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00003247 VK_RValue, OK_Ordinary, SourceLocation());
John McCall9d125032010-01-15 18:39:57 +00003248 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, DerefExpr->getType(),
John McCalla5bbc502010-11-15 09:46:46 +00003249 CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00003250 DerefExpr);
Steve Naroff621edce2009-04-29 16:37:50 +00003251 ReplaceStmt(Exp, castExpr);
3252 ProtocolExprDecls.insert(Exp->getProtocol());
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003253 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroff621edce2009-04-29 16:37:50 +00003254 return castExpr;
Mike Stump1eb44332009-09-09 15:08:12 +00003255
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00003256}
3257
Mike Stump1eb44332009-09-09 15:08:12 +00003258bool RewriteObjC::BufferContainsPPDirectives(const char *startBuf,
Steve Naroffbaf58c32008-05-31 14:15:04 +00003259 const char *endBuf) {
3260 while (startBuf < endBuf) {
3261 if (*startBuf == '#') {
3262 // Skip whitespace.
3263 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
3264 ;
3265 if (!strncmp(startBuf, "if", strlen("if")) ||
3266 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
3267 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
3268 !strncmp(startBuf, "define", strlen("define")) ||
3269 !strncmp(startBuf, "undef", strlen("undef")) ||
3270 !strncmp(startBuf, "else", strlen("else")) ||
3271 !strncmp(startBuf, "elif", strlen("elif")) ||
3272 !strncmp(startBuf, "endif", strlen("endif")) ||
3273 !strncmp(startBuf, "pragma", strlen("pragma")) ||
3274 !strncmp(startBuf, "include", strlen("include")) ||
3275 !strncmp(startBuf, "import", strlen("import")) ||
3276 !strncmp(startBuf, "include_next", strlen("include_next")))
3277 return true;
3278 }
3279 startBuf++;
3280 }
3281 return false;
3282}
3283
Fariborz Jahanian58457172011-12-05 18:43:13 +00003284/// RewriteObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003285/// an objective-c class with ivars.
Fariborz Jahanian58457172011-12-05 18:43:13 +00003286void RewriteObjC::RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003287 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003288 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
Daniel Dunbar4087f272010-08-17 22:39:59 +00003289 assert(CDecl->getName() != "" &&
Douglas Gregor2e1cd422008-11-17 14:58:09 +00003290 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian212b7682007-10-31 23:08:24 +00003291 // Do not synthesize more than once.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003292 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian212b7682007-10-31 23:08:24 +00003293 return;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003294 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Chris Lattnerf3a7af92008-03-16 21:08:55 +00003295 int NumIvars = CDecl->ivar_size();
Steve Narofffea763e82007-11-14 19:25:57 +00003296 SourceLocation LocStart = CDecl->getLocStart();
3297 SourceLocation LocEnd = CDecl->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +00003298
Steve Narofffea763e82007-11-14 19:25:57 +00003299 const char *startBuf = SM->getCharacterData(LocStart);
3300 const char *endBuf = SM->getCharacterData(LocEnd);
Mike Stump1eb44332009-09-09 15:08:12 +00003301
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00003302 // If no ivars and no root or if its root, directly or indirectly,
3303 // have no ivars (thus not synthesized) then no need to synthesize this class.
Chris Lattnerf3a7af92008-03-16 21:08:55 +00003304 if ((CDecl->isForwardDecl() || NumIvars == 0) &&
3305 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Chris Lattner2c78b872009-04-14 23:22:57 +00003306 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003307 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00003308 return;
3309 }
Mike Stump1eb44332009-09-09 15:08:12 +00003310
3311 // FIXME: This has potential of causing problem. If
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003312 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00003313 Result += "\nstruct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003314 Result += CDecl->getNameAsString();
Francois Pichet62ec1f22011-09-17 17:15:52 +00003315 if (LangOpts.MicrosoftExt)
Steve Naroff61ed9ca2008-03-10 23:16:54 +00003316 Result += "_IMPL";
Steve Naroff05b8c782008-03-12 00:25:36 +00003317
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00003318 if (NumIvars > 0) {
Steve Narofffea763e82007-11-14 19:25:57 +00003319 const char *cursor = strchr(startBuf, '{');
Mike Stump1eb44332009-09-09 15:08:12 +00003320 assert((cursor && endBuf)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003321 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Naroffbaf58c32008-05-31 14:15:04 +00003322 // If the buffer contains preprocessor directives, we do more fine-grained
3323 // rewrites. This is intended to fix code that looks like (which occurs in
3324 // NSURL.h, for example):
3325 //
3326 // #ifdef XYZ
3327 // @interface Foo : NSObject
3328 // #else
3329 // @interface FooBar : NSObject
3330 // #endif
3331 // {
3332 // int i;
3333 // }
3334 // @end
3335 //
3336 // This clause is segregated to avoid breaking the common case.
3337 if (BufferContainsPPDirectives(startBuf, cursor)) {
Mike Stump1eb44332009-09-09 15:08:12 +00003338 SourceLocation L = RCDecl ? CDecl->getSuperClassLoc() :
Argyrios Kyrtzidis1711fc92011-10-04 04:48:02 +00003339 CDecl->getAtStartLoc();
Steve Naroffbaf58c32008-05-31 14:15:04 +00003340 const char *endHeader = SM->getCharacterData(L);
Chris Lattner2c78b872009-04-14 23:22:57 +00003341 endHeader += Lexer::MeasureTokenLength(L, *SM, LangOpts);
Steve Naroffbaf58c32008-05-31 14:15:04 +00003342
Chris Lattnercafeb352009-02-20 18:18:36 +00003343 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroffbaf58c32008-05-31 14:15:04 +00003344 // advance to the end of the referenced protocols.
3345 while (endHeader < cursor && *endHeader != '>') endHeader++;
3346 endHeader++;
3347 }
3348 // rewrite the original header
Benjamin Kramerd999b372010-02-14 14:14:16 +00003349 ReplaceText(LocStart, endHeader-startBuf, Result);
Steve Naroffbaf58c32008-05-31 14:15:04 +00003350 } else {
3351 // rewrite the original header *without* disturbing the '{'
Benjamin Kramerd999b372010-02-14 14:14:16 +00003352 ReplaceText(LocStart, cursor-startBuf, Result);
Steve Naroffbaf58c32008-05-31 14:15:04 +00003353 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003354 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Narofffea763e82007-11-14 19:25:57 +00003355 Result = "\n struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003356 Result += RCDecl->getNameAsString();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00003357 Result += "_IMPL ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003358 Result += RCDecl->getNameAsString();
Steve Naroff819173c2008-03-12 21:22:52 +00003359 Result += "_IVARS;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003360
Steve Narofffea763e82007-11-14 19:25:57 +00003361 // insert the super class structure definition.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00003362 SourceLocation OnePastCurly =
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00003363 LocStart.getLocWithOffset(cursor-startBuf+1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003364 InsertText(OnePastCurly, Result);
Steve Narofffea763e82007-11-14 19:25:57 +00003365 }
3366 cursor++; // past '{'
Mike Stump1eb44332009-09-09 15:08:12 +00003367
Steve Narofffea763e82007-11-14 19:25:57 +00003368 // Now comment out any visibility specifiers.
3369 while (cursor < endBuf) {
3370 if (*cursor == '@') {
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00003371 SourceLocation atLoc = LocStart.getLocWithOffset(cursor-startBuf);
Chris Lattnerdf6a51b2007-11-14 22:57:51 +00003372 // Skip whitespace.
3373 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
3374 /*scan*/;
3375
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00003376 // FIXME: presence of @public, etc. inside comment results in
3377 // this transformation as well, which is still correct c-code.
Steve Narofffea763e82007-11-14 19:25:57 +00003378 if (!strncmp(cursor, "public", strlen("public")) ||
3379 !strncmp(cursor, "private", strlen("private")) ||
Steve Naroffc5e32772008-04-04 22:34:24 +00003380 !strncmp(cursor, "package", strlen("package")) ||
Fariborz Jahanian95673922007-11-14 22:26:25 +00003381 !strncmp(cursor, "protected", strlen("protected")))
Benjamin Kramerd999b372010-02-14 14:14:16 +00003382 InsertText(atLoc, "// ");
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00003383 }
Fariborz Jahanian95673922007-11-14 22:26:25 +00003384 // FIXME: If there are cases where '<' is used in ivar declaration part
3385 // of user code, then scan the ivar list and use needToScanForQualifiers
3386 // for type checking.
3387 else if (*cursor == '<') {
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00003388 SourceLocation atLoc = LocStart.getLocWithOffset(cursor-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003389 InsertText(atLoc, "/* ");
Fariborz Jahanian95673922007-11-14 22:26:25 +00003390 cursor = strchr(cursor, '>');
3391 cursor++;
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00003392 atLoc = LocStart.getLocWithOffset(cursor-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003393 InsertText(atLoc, " */");
Steve Naroffced80a82008-10-30 12:09:33 +00003394 } else if (*cursor == '^') { // rewrite block specifier.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00003395 SourceLocation caretLoc = LocStart.getLocWithOffset(cursor-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003396 ReplaceText(caretLoc, 1, "*");
Fariborz Jahanian95673922007-11-14 22:26:25 +00003397 }
Steve Narofffea763e82007-11-14 19:25:57 +00003398 cursor++;
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00003399 }
Steve Narofffea763e82007-11-14 19:25:57 +00003400 // Don't forget to add a ';'!!
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00003401 InsertText(LocEnd.getLocWithOffset(1), ";");
Steve Narofffea763e82007-11-14 19:25:57 +00003402 } else { // we don't have any instance variables - insert super struct.
Chris Lattner2c78b872009-04-14 23:22:57 +00003403 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Steve Narofffea763e82007-11-14 19:25:57 +00003404 Result += " {\n struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003405 Result += RCDecl->getNameAsString();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00003406 Result += "_IMPL ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003407 Result += RCDecl->getNameAsString();
Steve Naroff819173c2008-03-12 21:22:52 +00003408 Result += "_IVARS;\n};\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00003409 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003410 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003411 // Mark this struct as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003412 if (!ObjCSynthesizedStructs.insert(CDecl))
David Blaikieb219cfc2011-09-23 05:06:16 +00003413 llvm_unreachable("struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003414}
3415
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003416// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003417/// class methods.
Douglas Gregor653f1b12009-04-23 01:02:12 +00003418template<typename MethodIterator>
3419void RewriteObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
3420 MethodIterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00003421 bool IsInstanceMethod,
Chris Lattner5f9e2722011-07-23 10:55:15 +00003422 StringRef prefix,
3423 StringRef ClassName,
Chris Lattner158ecb92007-10-25 17:07:24 +00003424 std::string &Result) {
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003425 if (MethodBegin == MethodEnd) return;
Mike Stump1eb44332009-09-09 15:08:12 +00003426
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003427 if (!objc_impl_method) {
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003428 /* struct _objc_method {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003429 SEL _cmd;
3430 char *method_types;
3431 void *_imp;
3432 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003433 */
Chris Lattner158ecb92007-10-25 17:07:24 +00003434 Result += "\nstruct _objc_method {\n";
3435 Result += "\tSEL _cmd;\n";
3436 Result += "\tchar *method_types;\n";
3437 Result += "\tvoid *_imp;\n";
3438 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003439
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003440 objc_impl_method = true;
Fariborz Jahanian776d6ff2007-10-19 00:36:46 +00003441 }
Mike Stump1eb44332009-09-09 15:08:12 +00003442
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003443 // Build _objc_method_list for class's methods if needed
Mike Stump1eb44332009-09-09 15:08:12 +00003444
Steve Naroff946a6932008-03-11 00:12:29 +00003445 /* struct {
3446 struct _objc_method_list *next_method;
3447 int method_count;
3448 struct _objc_method method_list[];
3449 }
3450 */
Douglas Gregor653f1b12009-04-23 01:02:12 +00003451 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
Steve Naroff946a6932008-03-11 00:12:29 +00003452 Result += "\nstatic struct {\n";
3453 Result += "\tstruct _objc_method_list *next_method;\n";
3454 Result += "\tint method_count;\n";
3455 Result += "\tstruct _objc_method method_list[";
Douglas Gregor653f1b12009-04-23 01:02:12 +00003456 Result += utostr(NumMethods);
Steve Naroff946a6932008-03-11 00:12:29 +00003457 Result += "];\n} _OBJC_";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003458 Result += prefix;
3459 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
3460 Result += "_METHODS_";
3461 Result += ClassName;
Steve Naroffdbb65432008-03-12 17:18:30 +00003462 Result += " __attribute__ ((used, section (\"__OBJC, __";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003463 Result += IsInstanceMethod ? "inst" : "cls";
3464 Result += "_meth\")))= ";
Douglas Gregor653f1b12009-04-23 01:02:12 +00003465 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003466
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003467 Result += "\t,{{(SEL)\"";
Chris Lattner077bf5e2008-11-24 03:33:13 +00003468 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003469 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003470 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003471 Result += "\", \"";
3472 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00003473 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003474 Result += MethodInternalNames[*MethodBegin];
3475 Result += "}\n";
3476 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
3477 Result += "\t ,{(SEL)\"";
Chris Lattner077bf5e2008-11-24 03:33:13 +00003478 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003479 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003480 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003481 Result += "\", \"";
3482 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00003483 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003484 Result += MethodInternalNames[*MethodBegin];
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00003485 Result += "}\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003486 }
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003487 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003488}
3489
Steve Naroff621edce2009-04-29 16:37:50 +00003490/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
Chris Lattner780f3292008-07-21 21:32:27 +00003491void RewriteObjC::
Chris Lattner5f9e2722011-07-23 10:55:15 +00003492RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl, StringRef prefix,
3493 StringRef ClassName, std::string &Result) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003494 static bool objc_protocol_methods = false;
Steve Naroff621edce2009-04-29 16:37:50 +00003495
3496 // Output struct protocol_methods holder of method selector and type.
3497 if (!objc_protocol_methods && !PDecl->isForwardDecl()) {
3498 /* struct protocol_methods {
3499 SEL _cmd;
3500 char *method_types;
3501 }
3502 */
3503 Result += "\nstruct _protocol_methods {\n";
3504 Result += "\tstruct objc_selector *_cmd;\n";
3505 Result += "\tchar *method_types;\n";
3506 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003507
Steve Naroff621edce2009-04-29 16:37:50 +00003508 objc_protocol_methods = true;
3509 }
3510 // Do not synthesize the protocol more than once.
3511 if (ObjCSynthesizedProtocols.count(PDecl))
3512 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003513
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003514 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
3515 unsigned NumMethods = std::distance(PDecl->instmeth_begin(),
3516 PDecl->instmeth_end());
Steve Naroff621edce2009-04-29 16:37:50 +00003517 /* struct _objc_protocol_method_list {
3518 int protocol_method_count;
3519 struct protocol_methods protocols[];
3520 }
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00003521 */
Steve Naroff621edce2009-04-29 16:37:50 +00003522 Result += "\nstatic struct {\n";
3523 Result += "\tint protocol_method_count;\n";
3524 Result += "\tstruct _protocol_methods protocol_methods[";
3525 Result += utostr(NumMethods);
3526 Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
3527 Result += PDecl->getNameAsString();
3528 Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
3529 "{\n\t" + utostr(NumMethods) + "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003530
Steve Naroff621edce2009-04-29 16:37:50 +00003531 // Output instance methods declared in this protocol.
Mike Stump1eb44332009-09-09 15:08:12 +00003532 for (ObjCProtocolDecl::instmeth_iterator
3533 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
Steve Naroff621edce2009-04-29 16:37:50 +00003534 I != E; ++I) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003535 if (I == PDecl->instmeth_begin())
Steve Naroff621edce2009-04-29 16:37:50 +00003536 Result += "\t ,{{(struct objc_selector *)\"";
3537 else
3538 Result += "\t ,{(struct objc_selector *)\"";
Daniel Dunbar4087f272010-08-17 22:39:59 +00003539 Result += (*I)->getSelector().getAsString();
Steve Naroff621edce2009-04-29 16:37:50 +00003540 std::string MethodTypeString;
3541 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
3542 Result += "\", \"";
3543 Result += MethodTypeString;
3544 Result += "\"}\n";
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003545 }
Steve Naroff621edce2009-04-29 16:37:50 +00003546 Result += "\t }\n};\n";
3547 }
Mike Stump1eb44332009-09-09 15:08:12 +00003548
Steve Naroff621edce2009-04-29 16:37:50 +00003549 // Output class methods declared in this protocol.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003550 unsigned NumMethods = std::distance(PDecl->classmeth_begin(),
3551 PDecl->classmeth_end());
Steve Naroff621edce2009-04-29 16:37:50 +00003552 if (NumMethods > 0) {
3553 /* struct _objc_protocol_method_list {
3554 int protocol_method_count;
3555 struct protocol_methods protocols[];
3556 }
3557 */
3558 Result += "\nstatic struct {\n";
3559 Result += "\tint protocol_method_count;\n";
3560 Result += "\tstruct _protocol_methods protocol_methods[";
3561 Result += utostr(NumMethods);
3562 Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
3563 Result += PDecl->getNameAsString();
3564 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
3565 "{\n\t";
3566 Result += utostr(NumMethods);
3567 Result += "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003568
Steve Naroff621edce2009-04-29 16:37:50 +00003569 // Output instance methods declared in this protocol.
Mike Stump1eb44332009-09-09 15:08:12 +00003570 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003571 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
Steve Naroff621edce2009-04-29 16:37:50 +00003572 I != E; ++I) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003573 if (I == PDecl->classmeth_begin())
Steve Naroff621edce2009-04-29 16:37:50 +00003574 Result += "\t ,{{(struct objc_selector *)\"";
3575 else
3576 Result += "\t ,{(struct objc_selector *)\"";
Daniel Dunbar4087f272010-08-17 22:39:59 +00003577 Result += (*I)->getSelector().getAsString();
Steve Naroff621edce2009-04-29 16:37:50 +00003578 std::string MethodTypeString;
3579 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
3580 Result += "\", \"";
3581 Result += MethodTypeString;
3582 Result += "\"}\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003583 }
Steve Naroff621edce2009-04-29 16:37:50 +00003584 Result += "\t }\n};\n";
3585 }
3586
3587 // Output:
3588 /* struct _objc_protocol {
3589 // Objective-C 1.0 extensions
3590 struct _objc_protocol_extension *isa;
3591 char *protocol_name;
3592 struct _objc_protocol **protocol_list;
3593 struct _objc_protocol_method_list *instance_methods;
3594 struct _objc_protocol_method_list *class_methods;
Mike Stump1eb44332009-09-09 15:08:12 +00003595 };
Steve Naroff621edce2009-04-29 16:37:50 +00003596 */
3597 static bool objc_protocol = false;
3598 if (!objc_protocol) {
3599 Result += "\nstruct _objc_protocol {\n";
3600 Result += "\tstruct _objc_protocol_extension *isa;\n";
3601 Result += "\tchar *protocol_name;\n";
3602 Result += "\tstruct _objc_protocol **protocol_list;\n";
3603 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
3604 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003605 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003606
Steve Naroff621edce2009-04-29 16:37:50 +00003607 objc_protocol = true;
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003608 }
Mike Stump1eb44332009-09-09 15:08:12 +00003609
Steve Naroff621edce2009-04-29 16:37:50 +00003610 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
3611 Result += PDecl->getNameAsString();
3612 Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
3613 "{\n\t0, \"";
3614 Result += PDecl->getNameAsString();
3615 Result += "\", 0, ";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003616 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
Steve Naroff621edce2009-04-29 16:37:50 +00003617 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
3618 Result += PDecl->getNameAsString();
3619 Result += ", ";
3620 }
3621 else
3622 Result += "0, ";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003623 if (PDecl->classmeth_begin() != PDecl->classmeth_end()) {
Steve Naroff621edce2009-04-29 16:37:50 +00003624 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
3625 Result += PDecl->getNameAsString();
3626 Result += "\n";
3627 }
3628 else
3629 Result += "0\n";
3630 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003631
Steve Naroff621edce2009-04-29 16:37:50 +00003632 // Mark this protocol as having been generated.
3633 if (!ObjCSynthesizedProtocols.insert(PDecl))
David Blaikieb219cfc2011-09-23 05:06:16 +00003634 llvm_unreachable("protocol already synthesized");
Steve Naroff621edce2009-04-29 16:37:50 +00003635
3636}
3637
3638void RewriteObjC::
3639RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Protocols,
Chris Lattner5f9e2722011-07-23 10:55:15 +00003640 StringRef prefix, StringRef ClassName,
Steve Naroff621edce2009-04-29 16:37:50 +00003641 std::string &Result) {
3642 if (Protocols.empty()) return;
Mike Stump1eb44332009-09-09 15:08:12 +00003643
Steve Naroff621edce2009-04-29 16:37:50 +00003644 for (unsigned i = 0; i != Protocols.size(); i++)
3645 RewriteObjCProtocolMetaData(Protocols[i], prefix, ClassName, Result);
3646
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003647 // Output the top lovel protocol meta-data for the class.
3648 /* struct _objc_protocol_list {
3649 struct _objc_protocol_list *next;
3650 int protocol_count;
3651 struct _objc_protocol *class_protocols[];
3652 }
3653 */
3654 Result += "\nstatic struct {\n";
3655 Result += "\tstruct _objc_protocol_list *next;\n";
3656 Result += "\tint protocol_count;\n";
3657 Result += "\tstruct _objc_protocol *class_protocols[";
3658 Result += utostr(Protocols.size());
3659 Result += "];\n} _OBJC_";
3660 Result += prefix;
3661 Result += "_PROTOCOLS_";
3662 Result += ClassName;
3663 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
3664 "{\n\t0, ";
3665 Result += utostr(Protocols.size());
3666 Result += "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003667
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003668 Result += "\t,{&_OBJC_PROTOCOL_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003669 Result += Protocols[0]->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003670 Result += " \n";
Mike Stump1eb44332009-09-09 15:08:12 +00003671
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003672 for (unsigned i = 1; i != Protocols.size(); i++) {
3673 Result += "\t ,&_OBJC_PROTOCOL_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003674 Result += Protocols[i]->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003675 Result += "\n";
3676 }
3677 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003678}
3679
Steve Naroff621edce2009-04-29 16:37:50 +00003680
Mike Stump1eb44332009-09-09 15:08:12 +00003681/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003682/// implementation.
Steve Naroffb29b4272008-04-14 22:03:09 +00003683void RewriteObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003684 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003685 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003686 // Find category declaration for this implementation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003687 ObjCCategoryDecl *CDecl;
Mike Stump1eb44332009-09-09 15:08:12 +00003688 for (CDecl = ClassDecl->getCategoryList(); CDecl;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003689 CDecl = CDecl->getNextClassCategory())
3690 if (CDecl->getIdentifier() == IDecl->getIdentifier())
3691 break;
Mike Stump1eb44332009-09-09 15:08:12 +00003692
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003693 std::string FullCategoryName = ClassDecl->getNameAsString();
Chris Lattnereb44eee2007-12-23 01:40:15 +00003694 FullCategoryName += '_';
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003695 FullCategoryName += IDecl->getNameAsString();
Mike Stump1eb44332009-09-09 15:08:12 +00003696
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003697 // Build _objc_method_list for class's instance methods if needed
Chris Lattner5f9e2722011-07-23 10:55:15 +00003698 SmallVector<ObjCMethodDecl *, 32>
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003699 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
Douglas Gregor653f1b12009-04-23 01:02:12 +00003700
3701 // If any of our property implementations have associated getters or
3702 // setters, produce metadata for them as well.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003703 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
3704 PropEnd = IDecl->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00003705 Prop != PropEnd; ++Prop) {
3706 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
3707 continue;
3708 if (!(*Prop)->getPropertyIvarDecl())
3709 continue;
3710 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
3711 if (!PD)
3712 continue;
3713 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
3714 InstanceMethods.push_back(Getter);
3715 if (PD->isReadOnly())
3716 continue;
3717 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
3718 InstanceMethods.push_back(Setter);
3719 }
3720 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00003721 true, "CATEGORY_", FullCategoryName.c_str(),
3722 Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003723
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003724 // Build _objc_method_list for class's class methods if needed
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003725 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00003726 false, "CATEGORY_", FullCategoryName.c_str(),
3727 Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003728
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003729 // Protocols referenced in class declaration?
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00003730 // Null CDecl is case of a category implementation with no category interface
3731 if (CDecl)
Steve Naroff621edce2009-04-29 16:37:50 +00003732 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(), "CATEGORY",
Daniel Dunbar4087f272010-08-17 22:39:59 +00003733 FullCategoryName, Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003734 /* struct _objc_category {
3735 char *category_name;
3736 char *class_name;
3737 struct _objc_method_list *instance_methods;
3738 struct _objc_method_list *class_methods;
3739 struct _objc_protocol_list *protocols;
3740 // Objective-C 1.0 extensions
3741 uint32_t size; // sizeof (struct _objc_category)
Mike Stump1eb44332009-09-09 15:08:12 +00003742 struct _objc_property_list *instance_properties; // category's own
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003743 // @property decl.
Mike Stump1eb44332009-09-09 15:08:12 +00003744 };
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003745 */
Mike Stump1eb44332009-09-09 15:08:12 +00003746
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003747 static bool objc_category = false;
3748 if (!objc_category) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003749 Result += "\nstruct _objc_category {\n";
3750 Result += "\tchar *category_name;\n";
3751 Result += "\tchar *class_name;\n";
3752 Result += "\tstruct _objc_method_list *instance_methods;\n";
3753 Result += "\tstruct _objc_method_list *class_methods;\n";
3754 Result += "\tstruct _objc_protocol_list *protocols;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003755 Result += "\tunsigned int size;\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003756 Result += "\tstruct _objc_property_list *instance_properties;\n";
3757 Result += "};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003758 objc_category = true;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003759 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003760 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
3761 Result += FullCategoryName;
Steve Naroffdbb65432008-03-12 17:18:30 +00003762 Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003763 Result += IDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003764 Result += "\"\n\t, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003765 Result += ClassDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003766 Result += "\"\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003767
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003768 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003769 Result += "\t, (struct _objc_method_list *)"
3770 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
3771 Result += FullCategoryName;
3772 Result += "\n";
3773 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003774 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003775 Result += "\t, 0\n";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003776 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003777 Result += "\t, (struct _objc_method_list *)"
3778 "&_OBJC_CATEGORY_CLASS_METHODS_";
3779 Result += FullCategoryName;
3780 Result += "\n";
3781 }
3782 else
3783 Result += "\t, 0\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003784
Chris Lattnercafeb352009-02-20 18:18:36 +00003785 if (CDecl && CDecl->protocol_begin() != CDecl->protocol_end()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003786 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003787 Result += FullCategoryName;
3788 Result += "\n";
3789 }
3790 else
3791 Result += "\t, 0\n";
3792 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003793}
3794
Fariborz Jahanian58457172011-12-05 18:43:13 +00003795/// RewriteIvarOffsetComputation - This rutine synthesizes computation of
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003796/// ivar offset.
Fariborz Jahanian58457172011-12-05 18:43:13 +00003797void RewriteObjC::RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003798 std::string &Result) {
Steve Naroff8f3b2652008-07-16 18:22:22 +00003799 if (ivar->isBitField()) {
3800 // FIXME: The hack below doesn't work for bitfields. For now, we simply
3801 // place all bitfields at offset 0.
3802 Result += "0";
3803 } else {
3804 Result += "__OFFSETOFIVAR__(struct ";
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00003805 Result += ivar->getContainingInterface()->getNameAsString();
Francois Pichet62ec1f22011-09-17 17:15:52 +00003806 if (LangOpts.MicrosoftExt)
Steve Naroff8f3b2652008-07-16 18:22:22 +00003807 Result += "_IMPL";
3808 Result += ", ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003809 Result += ivar->getNameAsString();
Steve Naroff8f3b2652008-07-16 18:22:22 +00003810 Result += ")";
3811 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003812}
3813
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003814//===----------------------------------------------------------------------===//
3815// Meta Data Emission
3816//===----------------------------------------------------------------------===//
3817
Steve Naroffb29b4272008-04-14 22:03:09 +00003818void RewriteObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003819 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003820 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
Mike Stump1eb44332009-09-09 15:08:12 +00003821
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00003822 // Explicitly declared @interface's are already synthesized.
Steve Naroff33feeb02009-04-20 20:09:33 +00003823 if (CDecl->isImplicitInterfaceDecl()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003824 // FIXME: Implementation of a class with no @interface (legacy) doese not
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00003825 // produce correct synthesis as yet.
Fariborz Jahanian58457172011-12-05 18:43:13 +00003826 RewriteObjCInternalStruct(CDecl, Result);
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00003827 }
Mike Stump1eb44332009-09-09 15:08:12 +00003828
Chris Lattnerbe6df082007-12-12 07:56:42 +00003829 // Build _objc_ivar_list metadata for classes ivars if needed
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003830 unsigned NumIvars = !IDecl->ivar_empty()
Mike Stump1eb44332009-09-09 15:08:12 +00003831 ? IDecl->ivar_size()
Chris Lattnerf3a7af92008-03-16 21:08:55 +00003832 : (CDecl ? CDecl->ivar_size() : 0);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003833 if (NumIvars > 0) {
3834 static bool objc_ivar = false;
3835 if (!objc_ivar) {
3836 /* struct _objc_ivar {
3837 char *ivar_name;
3838 char *ivar_type;
3839 int ivar_offset;
Mike Stump1eb44332009-09-09 15:08:12 +00003840 };
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003841 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003842 Result += "\nstruct _objc_ivar {\n";
3843 Result += "\tchar *ivar_name;\n";
3844 Result += "\tchar *ivar_type;\n";
3845 Result += "\tint ivar_offset;\n";
3846 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003847
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003848 objc_ivar = true;
3849 }
3850
Steve Naroff946a6932008-03-11 00:12:29 +00003851 /* struct {
3852 int ivar_count;
3853 struct _objc_ivar ivar_list[nIvars];
Mike Stump1eb44332009-09-09 15:08:12 +00003854 };
Steve Naroff946a6932008-03-11 00:12:29 +00003855 */
Mike Stump1eb44332009-09-09 15:08:12 +00003856 Result += "\nstatic struct {\n";
Steve Naroff946a6932008-03-11 00:12:29 +00003857 Result += "\tint ivar_count;\n";
3858 Result += "\tstruct _objc_ivar ivar_list[";
3859 Result += utostr(NumIvars);
3860 Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003861 Result += IDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00003862 Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003863 "{\n\t";
3864 Result += utostr(NumIvars);
3865 Result += "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003866
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003867 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003868 SmallVector<ObjCIvarDecl *, 8> IVars;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003869 if (!IDecl->ivar_empty()) {
Fariborz Jahanian11062e12010-02-19 00:31:17 +00003870 for (ObjCInterfaceDecl::ivar_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003871 IV = IDecl->ivar_begin(), IVEnd = IDecl->ivar_end();
Douglas Gregor8f36aba2009-04-23 03:23:08 +00003872 IV != IVEnd; ++IV)
3873 IVars.push_back(*IV);
Fariborz Jahanian11062e12010-02-19 00:31:17 +00003874 IVI = IDecl->ivar_begin();
3875 IVE = IDecl->ivar_end();
Chris Lattnerbe6df082007-12-12 07:56:42 +00003876 } else {
3877 IVI = CDecl->ivar_begin();
3878 IVE = CDecl->ivar_end();
3879 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003880 Result += "\t,{{\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003881 Result += (*IVI)->getNameAsString();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003882 Result += "\", \"";
Steve Naroff621edce2009-04-29 16:37:50 +00003883 std::string TmpString, StrEncoding;
3884 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
3885 QuoteDoublequotes(TmpString, StrEncoding);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003886 Result += StrEncoding;
3887 Result += "\", ";
Fariborz Jahanian58457172011-12-05 18:43:13 +00003888 RewriteIvarOffsetComputation(*IVI, Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003889 Result += "}\n";
Chris Lattnerbe6df082007-12-12 07:56:42 +00003890 for (++IVI; IVI != IVE; ++IVI) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003891 Result += "\t ,{\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003892 Result += (*IVI)->getNameAsString();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003893 Result += "\", \"";
Steve Naroff621edce2009-04-29 16:37:50 +00003894 std::string TmpString, StrEncoding;
3895 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
3896 QuoteDoublequotes(TmpString, StrEncoding);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003897 Result += StrEncoding;
3898 Result += "\", ";
Fariborz Jahanian58457172011-12-05 18:43:13 +00003899 RewriteIvarOffsetComputation((*IVI), Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003900 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003901 }
Mike Stump1eb44332009-09-09 15:08:12 +00003902
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003903 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003904 }
Mike Stump1eb44332009-09-09 15:08:12 +00003905
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003906 // Build _objc_method_list for class's instance methods if needed
Chris Lattner5f9e2722011-07-23 10:55:15 +00003907 SmallVector<ObjCMethodDecl *, 32>
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003908 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
Douglas Gregor653f1b12009-04-23 01:02:12 +00003909
3910 // If any of our property implementations have associated getters or
3911 // setters, produce metadata for them as well.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003912 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
3913 PropEnd = IDecl->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00003914 Prop != PropEnd; ++Prop) {
3915 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
3916 continue;
3917 if (!(*Prop)->getPropertyIvarDecl())
3918 continue;
3919 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
3920 if (!PD)
3921 continue;
3922 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
Fariborz Jahanianec3683b2010-10-19 23:47:54 +00003923 if (!Getter->isDefined())
3924 InstanceMethods.push_back(Getter);
Douglas Gregor653f1b12009-04-23 01:02:12 +00003925 if (PD->isReadOnly())
3926 continue;
3927 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
Fariborz Jahanianec3683b2010-10-19 23:47:54 +00003928 if (!Setter->isDefined())
3929 InstanceMethods.push_back(Setter);
Douglas Gregor653f1b12009-04-23 01:02:12 +00003930 }
3931 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
Daniel Dunbar4087f272010-08-17 22:39:59 +00003932 true, "", IDecl->getName(), Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003933
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003934 // Build _objc_method_list for class's class methods if needed
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003935 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Daniel Dunbar4087f272010-08-17 22:39:59 +00003936 false, "", IDecl->getName(), Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003937
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003938 // Protocols referenced in class declaration?
Steve Naroff621edce2009-04-29 16:37:50 +00003939 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(),
Daniel Dunbar4087f272010-08-17 22:39:59 +00003940 "CLASS", CDecl->getName(), Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003941
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003942 // Declaration of class/meta-class metadata
3943 /* struct _objc_class {
3944 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003945 const char *super_class_name;
3946 char *name;
3947 long version;
3948 long info;
3949 long instance_size;
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003950 struct _objc_ivar_list *ivars;
3951 struct _objc_method_list *methods;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003952 struct objc_cache *cache;
3953 struct objc_protocol_list *protocols;
3954 const char *ivar_layout;
3955 struct _objc_class_ext *ext;
Mike Stump1eb44332009-09-09 15:08:12 +00003956 };
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003957 */
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003958 static bool objc_class = false;
3959 if (!objc_class) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003960 Result += "\nstruct _objc_class {\n";
3961 Result += "\tstruct _objc_class *isa;\n";
3962 Result += "\tconst char *super_class_name;\n";
3963 Result += "\tchar *name;\n";
3964 Result += "\tlong version;\n";
3965 Result += "\tlong info;\n";
3966 Result += "\tlong instance_size;\n";
3967 Result += "\tstruct _objc_ivar_list *ivars;\n";
3968 Result += "\tstruct _objc_method_list *methods;\n";
3969 Result += "\tstruct objc_cache *cache;\n";
3970 Result += "\tstruct _objc_protocol_list *protocols;\n";
3971 Result += "\tconst char *ivar_layout;\n";
3972 Result += "\tstruct _objc_class_ext *ext;\n";
3973 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003974 objc_class = true;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003975 }
Mike Stump1eb44332009-09-09 15:08:12 +00003976
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003977 // Meta-class metadata generation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003978 ObjCInterfaceDecl *RootClass = 0;
3979 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003980 while (SuperClass) {
3981 RootClass = SuperClass;
3982 SuperClass = SuperClass->getSuperClass();
3983 }
3984 SuperClass = CDecl->getSuperClass();
Mike Stump1eb44332009-09-09 15:08:12 +00003985
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003986 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003987 Result += CDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00003988 Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003989 "{\n\t(struct _objc_class *)\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003990 Result += (RootClass ? RootClass->getNameAsString() : CDecl->getNameAsString());
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003991 Result += "\"";
3992
3993 if (SuperClass) {
3994 Result += ", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003995 Result += SuperClass->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003996 Result += "\", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003997 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003998 Result += "\"";
3999 }
4000 else {
4001 Result += ", 0, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004002 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004003 Result += "\"";
4004 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004005 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00004006 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004007 Result += ", 0,2, sizeof(struct _objc_class), 0";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004008 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
Steve Naroff23f41272008-03-11 18:14:26 +00004009 Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004010 Result += IDecl->getNameAsString();
Mike Stump1eb44332009-09-09 15:08:12 +00004011 Result += "\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004012 }
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00004013 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004014 Result += ", 0\n";
Chris Lattnercafeb352009-02-20 18:18:36 +00004015 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00004016 Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004017 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004018 Result += ",0,0\n";
4019 }
Fariborz Jahanian454cb012007-10-24 20:54:23 +00004020 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004021 Result += "\t,0,0,0,0\n";
4022 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004023
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00004024 // class metadata generation.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004025 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004026 Result += CDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00004027 Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004028 "{\n\t&_OBJC_METACLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004029 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004030 if (SuperClass) {
4031 Result += ", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004032 Result += SuperClass->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004033 Result += "\", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004034 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004035 Result += "\"";
4036 }
4037 else {
4038 Result += ", 0, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004039 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004040 Result += "\"";
4041 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00004042 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00004043 Result += ", 0,1";
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004044 if (!ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00004045 Result += ",0";
4046 else {
4047 // class has size. Must synthesize its size.
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00004048 Result += ",sizeof(struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004049 Result += CDecl->getNameAsString();
Francois Pichet62ec1f22011-09-17 17:15:52 +00004050 if (LangOpts.MicrosoftExt)
Steve Naroffba9ac4e2008-03-10 23:33:22 +00004051 Result += "_IMPL";
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00004052 Result += ")";
4053 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004054 if (NumIvars > 0) {
Steve Naroffc0a123c2008-03-11 17:37:02 +00004055 Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004056 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004057 Result += "\n\t";
4058 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00004059 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004060 Result += ",0";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004061 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
Steve Naroff946a6932008-03-11 00:12:29 +00004062 Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004063 Result += CDecl->getNameAsString();
Mike Stump1eb44332009-09-09 15:08:12 +00004064 Result += ", 0\n\t";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004065 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00004066 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004067 Result += ",0,0";
Chris Lattnercafeb352009-02-20 18:18:36 +00004068 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00004069 Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004070 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004071 Result += ", 0,0\n";
4072 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00004073 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004074 Result += ",0,0,0\n";
4075 Result += "};\n";
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00004076}
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00004077
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00004078/// RewriteImplementations - This routine rewrites all method implementations
4079/// and emits meta-data.
4080
Steve Narofface66252008-11-13 20:07:04 +00004081void RewriteObjC::RewriteImplementations() {
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00004082 int ClsDefCount = ClassImplementation.size();
4083 int CatDefCount = CategoryImplementation.size();
Mike Stump1eb44332009-09-09 15:08:12 +00004084
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00004085 // Rewrite implemented methods
4086 for (int i = 0; i < ClsDefCount; i++)
4087 RewriteImplementationDecl(ClassImplementation[i]);
Mike Stump1eb44332009-09-09 15:08:12 +00004088
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00004089 for (int i = 0; i < CatDefCount; i++)
4090 RewriteImplementationDecl(CategoryImplementation[i]);
Steve Narofface66252008-11-13 20:07:04 +00004091}
Mike Stump1eb44332009-09-09 15:08:12 +00004092
Fariborz Jahanian58457172011-12-05 18:43:13 +00004093void RewriteObjC::RewriteMetaDataIntoBuffer(std::string &Result) {
Steve Narofface66252008-11-13 20:07:04 +00004094 int ClsDefCount = ClassImplementation.size();
4095 int CatDefCount = CategoryImplementation.size();
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00004096
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00004097 // For each implemented class, write out all its meta data.
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00004098 for (int i = 0; i < ClsDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004099 RewriteObjCClassMetaData(ClassImplementation[i], Result);
Mike Stump1eb44332009-09-09 15:08:12 +00004100
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00004101 // For each implemented category, write out all its meta data.
4102 for (int i = 0; i < CatDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004103 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
Steve Naroff621edce2009-04-29 16:37:50 +00004104
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00004105 // Write objc_symtab metadata
4106 /*
4107 struct _objc_symtab
4108 {
4109 long sel_ref_cnt;
4110 SEL *refs;
4111 short cls_def_cnt;
4112 short cat_def_cnt;
4113 void *defs[cls_def_cnt + cat_def_cnt];
Mike Stump1eb44332009-09-09 15:08:12 +00004114 };
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00004115 */
Mike Stump1eb44332009-09-09 15:08:12 +00004116
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004117 Result += "\nstruct _objc_symtab {\n";
4118 Result += "\tlong sel_ref_cnt;\n";
4119 Result += "\tSEL *refs;\n";
4120 Result += "\tshort cls_def_cnt;\n";
4121 Result += "\tshort cat_def_cnt;\n";
4122 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
4123 Result += "};\n\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004124
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004125 Result += "static struct _objc_symtab "
Steve Naroffdbb65432008-03-12 17:18:30 +00004126 "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004127 Result += "\t0, 0, " + utostr(ClsDefCount)
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004128 + ", " + utostr(CatDefCount) + "\n";
4129 for (int i = 0; i < ClsDefCount; i++) {
4130 Result += "\t,&_OBJC_CLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004131 Result += ClassImplementation[i]->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004132 Result += "\n";
4133 }
Mike Stump1eb44332009-09-09 15:08:12 +00004134
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004135 for (int i = 0; i < CatDefCount; i++) {
4136 Result += "\t,&_OBJC_CATEGORY_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004137 Result += CategoryImplementation[i]->getClassInterface()->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004138 Result += "_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004139 Result += CategoryImplementation[i]->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004140 Result += "\n";
4141 }
Mike Stump1eb44332009-09-09 15:08:12 +00004142
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004143 Result += "};\n\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004144
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00004145 // Write objc_module metadata
Mike Stump1eb44332009-09-09 15:08:12 +00004146
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00004147 /*
4148 struct _objc_module {
4149 long version;
4150 long size;
4151 const char *name;
4152 struct _objc_symtab *symtab;
4153 }
4154 */
Mike Stump1eb44332009-09-09 15:08:12 +00004155
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004156 Result += "\nstruct _objc_module {\n";
4157 Result += "\tlong version;\n";
4158 Result += "\tlong size;\n";
4159 Result += "\tconst char *name;\n";
4160 Result += "\tstruct _objc_symtab *symtab;\n";
4161 Result += "};\n\n";
4162 Result += "static struct _objc_module "
Steve Naroffdbb65432008-03-12 17:18:30 +00004163 "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004164 Result += "\t" + utostr(OBJC_ABI_VERSION) +
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00004165 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004166 Result += "};\n\n";
Steve Naroff4f943c22008-03-10 20:43:59 +00004167
Francois Pichet62ec1f22011-09-17 17:15:52 +00004168 if (LangOpts.MicrosoftExt) {
Steve Naroff621edce2009-04-29 16:37:50 +00004169 if (ProtocolExprDecls.size()) {
4170 Result += "#pragma section(\".objc_protocol$B\",long,read,write)\n";
4171 Result += "#pragma data_seg(push, \".objc_protocol$B\")\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004172 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Steve Naroff621edce2009-04-29 16:37:50 +00004173 E = ProtocolExprDecls.end(); I != E; ++I) {
4174 Result += "static struct _objc_protocol *_POINTER_OBJC_PROTOCOL_";
4175 Result += (*I)->getNameAsString();
4176 Result += " = &_OBJC_PROTOCOL_";
4177 Result += (*I)->getNameAsString();
4178 Result += ";\n";
4179 }
4180 Result += "#pragma data_seg(pop)\n\n";
4181 }
Steve Naroff4f943c22008-03-10 20:43:59 +00004182 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
Steve Naroff19190322008-05-07 00:06:16 +00004183 Result += "#pragma data_seg(push, \".objc_module_info$B\")\n";
Steve Naroff4f943c22008-03-10 20:43:59 +00004184 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
4185 Result += "&_OBJC_MODULES;\n";
4186 Result += "#pragma data_seg(pop)\n\n";
4187 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00004188}
Chris Lattner311ff022007-10-16 22:36:42 +00004189
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004190void RewriteObjC::RewriteByRefString(std::string &ResultStr,
4191 const std::string &Name,
Fariborz Jahanian1e8011e2011-01-27 23:18:15 +00004192 ValueDecl *VD, bool def) {
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004193 assert(BlockByRefDeclNo.count(VD) &&
4194 "RewriteByRefString: ByRef decl missing");
Fariborz Jahanian1e8011e2011-01-27 23:18:15 +00004195 if (def)
4196 ResultStr += "struct ";
4197 ResultStr += "__Block_byref_" + Name +
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004198 "_" + utostr(BlockByRefDeclNo[VD]) ;
4199}
4200
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004201static bool HasLocalVariableExternalStorage(ValueDecl *VD) {
4202 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4203 return (Var->isFunctionOrMethodVarDecl() && !Var->hasLocalStorage());
4204 return false;
4205}
4206
Steve Naroff54055232008-10-27 17:20:55 +00004207std::string RewriteObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
Chris Lattner5f9e2722011-07-23 10:55:15 +00004208 StringRef funcName,
Steve Naroff54055232008-10-27 17:20:55 +00004209 std::string Tag) {
4210 const FunctionType *AFT = CE->getFunctionType();
4211 QualType RT = AFT->getResultType();
4212 std::string StructRef = "struct " + Tag;
Douglas Gregor30c42402011-09-27 22:38:19 +00004213 std::string S = "static " + RT.getAsString(Context->getPrintingPolicy()) + " __" +
Daniel Dunbar4087f272010-08-17 22:39:59 +00004214 funcName.str() + "_" + "block_func_" + utostr(i);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00004215
Steve Naroff54055232008-10-27 17:20:55 +00004216 BlockDecl *BD = CE->getBlockDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00004217
Douglas Gregor72564e72009-02-26 23:50:07 +00004218 if (isa<FunctionNoProtoType>(AFT)) {
Mike Stump1eb44332009-09-09 15:08:12 +00004219 // No user-supplied arguments. Still need to pass in a pointer to the
Steve Naroffdf8570d2009-02-02 17:19:26 +00004220 // block (to reference imported block decl refs).
4221 S += "(" + StructRef + " *__cself)";
Steve Naroff54055232008-10-27 17:20:55 +00004222 } else if (BD->param_empty()) {
4223 S += "(" + StructRef + " *__cself)";
4224 } else {
Douglas Gregor72564e72009-02-26 23:50:07 +00004225 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
Steve Naroff54055232008-10-27 17:20:55 +00004226 assert(FT && "SynthesizeBlockFunc: No function proto");
4227 S += '(';
4228 // first add the implicit argument.
4229 S += StructRef + " *__cself, ";
4230 std::string ParamStr;
4231 for (BlockDecl::param_iterator AI = BD->param_begin(),
4232 E = BD->param_end(); AI != E; ++AI) {
4233 if (AI != BD->param_begin()) S += ", ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004234 ParamStr = (*AI)->getNameAsString();
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004235 QualType QT = (*AI)->getType();
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00004236 if (convertBlockPointerToFunctionPointer(QT))
Douglas Gregor30c42402011-09-27 22:38:19 +00004237 QT.getAsStringInternal(ParamStr, Context->getPrintingPolicy());
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004238 else
Douglas Gregor30c42402011-09-27 22:38:19 +00004239 QT.getAsStringInternal(ParamStr, Context->getPrintingPolicy());
Steve Naroff54055232008-10-27 17:20:55 +00004240 S += ParamStr;
4241 }
4242 if (FT->isVariadic()) {
4243 if (!BD->param_empty()) S += ", ";
4244 S += "...";
4245 }
4246 S += ')';
4247 }
4248 S += " {\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004249
Steve Naroff54055232008-10-27 17:20:55 +00004250 // Create local declarations to avoid rewriting all closure decl ref exprs.
4251 // First, emit a declaration for all "by ref" decls.
Chris Lattner5f9e2722011-07-23 10:55:15 +00004252 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004253 E = BlockByRefDecls.end(); I != E; ++I) {
4254 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004255 std::string Name = (*I)->getNameAsString();
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004256 std::string TypeString;
4257 RewriteByRefString(TypeString, Name, (*I));
4258 TypeString += " *";
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004259 Name = TypeString + Name;
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004260 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004261 }
Steve Naroff54055232008-10-27 17:20:55 +00004262 // Next, emit a declaration for all "by copy" declarations.
Chris Lattner5f9e2722011-07-23 10:55:15 +00004263 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004264 E = BlockByCopyDecls.end(); I != E; ++I) {
4265 S += " ";
Steve Naroff54055232008-10-27 17:20:55 +00004266 // Handle nested closure invocation. For example:
4267 //
4268 // void (^myImportedClosure)(void);
4269 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
Mike Stump1eb44332009-09-09 15:08:12 +00004270 //
Steve Naroff54055232008-10-27 17:20:55 +00004271 // void (^anotherClosure)(void);
4272 // anotherClosure = ^(void) {
4273 // myImportedClosure(); // import and invoke the closure
4274 // };
4275 //
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00004276 if (isTopLevelBlockPointerType((*I)->getType())) {
4277 RewriteBlockPointerTypeVariable(S, (*I));
4278 S += " = (";
4279 RewriteBlockPointerType(S, (*I)->getType());
4280 S += ")";
4281 S += "__cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
4282 }
4283 else {
Fariborz Jahanian210c2482010-02-16 17:26:03 +00004284 std::string Name = (*I)->getNameAsString();
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004285 QualType QT = (*I)->getType();
4286 if (HasLocalVariableExternalStorage(*I))
4287 QT = Context->getPointerType(QT);
Douglas Gregor30c42402011-09-27 22:38:19 +00004288 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00004289 S += Name + " = __cself->" +
4290 (*I)->getNameAsString() + "; // bound by copy\n";
4291 }
Steve Naroff54055232008-10-27 17:20:55 +00004292 }
4293 std::string RewrittenStr = RewrittenBlockExprs[CE];
4294 const char *cstr = RewrittenStr.c_str();
4295 while (*cstr++ != '{') ;
4296 S += cstr;
4297 S += "\n";
4298 return S;
4299}
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00004300
Steve Naroff54055232008-10-27 17:20:55 +00004301std::string RewriteObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
Chris Lattner5f9e2722011-07-23 10:55:15 +00004302 StringRef funcName,
Steve Naroff54055232008-10-27 17:20:55 +00004303 std::string Tag) {
4304 std::string StructRef = "struct " + Tag;
4305 std::string S = "static void __";
Mike Stump1eb44332009-09-09 15:08:12 +00004306
Steve Naroff54055232008-10-27 17:20:55 +00004307 S += funcName;
4308 S += "_block_copy_" + utostr(i);
4309 S += "(" + StructRef;
4310 S += "*dst, " + StructRef;
4311 S += "*src) {";
Mike Stump1eb44332009-09-09 15:08:12 +00004312 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004313 E = ImportedBlockDecls.end(); I != E; ++I) {
Fariborz Jahaniana3f61ae2011-07-30 01:21:41 +00004314 ValueDecl *VD = (*I);
Steve Naroff5bc60d02008-12-16 15:50:30 +00004315 S += "_Block_object_assign((void*)&dst->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004316 S += (*I)->getNameAsString();
Steve Naroff47a24222008-12-11 20:51:38 +00004317 S += ", (void*)src->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004318 S += (*I)->getNameAsString();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004319 if (BlockByRefDeclsPtrSet.count((*I)))
Fariborz Jahanian73e437b2009-12-23 21:18:41 +00004320 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
Fariborz Jahaniana3f61ae2011-07-30 01:21:41 +00004321 else if (VD->getType()->isBlockPointerType())
Fariborz Jahanian06433c62011-07-30 01:07:55 +00004322 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
Fariborz Jahaniana3f61ae2011-07-30 01:21:41 +00004323 else
4324 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff54055232008-10-27 17:20:55 +00004325 }
Fariborz Jahaniand25d1b52009-12-23 20:32:38 +00004326 S += "}\n";
4327
Steve Naroff54055232008-10-27 17:20:55 +00004328 S += "\nstatic void __";
4329 S += funcName;
4330 S += "_block_dispose_" + utostr(i);
4331 S += "(" + StructRef;
4332 S += "*src) {";
Mike Stump1eb44332009-09-09 15:08:12 +00004333 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004334 E = ImportedBlockDecls.end(); I != E; ++I) {
Fariborz Jahaniana3f61ae2011-07-30 01:21:41 +00004335 ValueDecl *VD = (*I);
Steve Naroff5bc60d02008-12-16 15:50:30 +00004336 S += "_Block_object_dispose((void*)src->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004337 S += (*I)->getNameAsString();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004338 if (BlockByRefDeclsPtrSet.count((*I)))
Fariborz Jahanian73e437b2009-12-23 21:18:41 +00004339 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
Fariborz Jahaniana3f61ae2011-07-30 01:21:41 +00004340 else if (VD->getType()->isBlockPointerType())
Fariborz Jahanian06433c62011-07-30 01:07:55 +00004341 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
Fariborz Jahaniana3f61ae2011-07-30 01:21:41 +00004342 else
4343 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff54055232008-10-27 17:20:55 +00004344 }
Mike Stump1eb44332009-09-09 15:08:12 +00004345 S += "}\n";
Steve Naroff54055232008-10-27 17:20:55 +00004346 return S;
4347}
4348
Steve Naroff01aec112009-12-06 21:14:13 +00004349std::string RewriteObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
4350 std::string Desc) {
Steve Naroffced80a82008-10-30 12:09:33 +00004351 std::string S = "\nstruct " + Tag;
Steve Naroff54055232008-10-27 17:20:55 +00004352 std::string Constructor = " " + Tag;
Mike Stump1eb44332009-09-09 15:08:12 +00004353
Steve Naroff54055232008-10-27 17:20:55 +00004354 S += " {\n struct __block_impl impl;\n";
Steve Naroff01aec112009-12-06 21:14:13 +00004355 S += " struct " + Desc;
4356 S += "* Desc;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004357
Steve Naroff01aec112009-12-06 21:14:13 +00004358 Constructor += "(void *fp, "; // Invoke function pointer.
4359 Constructor += "struct " + Desc; // Descriptor pointer.
4360 Constructor += " *desc";
Mike Stump1eb44332009-09-09 15:08:12 +00004361
Steve Naroff54055232008-10-27 17:20:55 +00004362 if (BlockDeclRefs.size()) {
4363 // Output all "by copy" declarations.
Chris Lattner5f9e2722011-07-23 10:55:15 +00004364 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004365 E = BlockByCopyDecls.end(); I != E; ++I) {
4366 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004367 std::string FieldName = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00004368 std::string ArgName = "_" + FieldName;
4369 // Handle nested closure invocation. For example:
4370 //
4371 // void (^myImportedBlock)(void);
4372 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
Mike Stump1eb44332009-09-09 15:08:12 +00004373 //
Steve Naroff54055232008-10-27 17:20:55 +00004374 // void (^anotherBlock)(void);
4375 // anotherBlock = ^(void) {
4376 // myImportedBlock(); // import and invoke the closure
4377 // };
4378 //
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004379 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff54055232008-10-27 17:20:55 +00004380 S += "struct __block_impl *";
4381 Constructor += ", void *" + ArgName;
4382 } else {
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004383 QualType QT = (*I)->getType();
4384 if (HasLocalVariableExternalStorage(*I))
4385 QT = Context->getPointerType(QT);
Douglas Gregor30c42402011-09-27 22:38:19 +00004386 QT.getAsStringInternal(FieldName, Context->getPrintingPolicy());
4387 QT.getAsStringInternal(ArgName, Context->getPrintingPolicy());
Steve Naroff54055232008-10-27 17:20:55 +00004388 Constructor += ", " + ArgName;
4389 }
4390 S += FieldName + ";\n";
4391 }
4392 // Output all "by ref" declarations.
Chris Lattner5f9e2722011-07-23 10:55:15 +00004393 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004394 E = BlockByRefDecls.end(); I != E; ++I) {
4395 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004396 std::string FieldName = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00004397 std::string ArgName = "_" + FieldName;
Fariborz Jahanian651ba522011-04-01 23:08:13 +00004398 {
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004399 std::string TypeString;
4400 RewriteByRefString(TypeString, FieldName, (*I));
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004401 TypeString += " *";
4402 FieldName = TypeString + FieldName;
4403 ArgName = TypeString + ArgName;
Steve Naroff54055232008-10-27 17:20:55 +00004404 Constructor += ", " + ArgName;
4405 }
4406 S += FieldName + "; // by ref\n";
4407 }
4408 // Finish writing the constructor.
Fariborz Jahanian20432ef2010-07-28 23:27:30 +00004409 Constructor += ", int flags=0)";
4410 // Initialize all "by copy" arguments.
4411 bool firsTime = true;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004412 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Fariborz Jahanian20432ef2010-07-28 23:27:30 +00004413 E = BlockByCopyDecls.end(); I != E; ++I) {
4414 std::string Name = (*I)->getNameAsString();
4415 if (firsTime) {
4416 Constructor += " : ";
4417 firsTime = false;
4418 }
4419 else
4420 Constructor += ", ";
4421 if (isTopLevelBlockPointerType((*I)->getType()))
4422 Constructor += Name + "((struct __block_impl *)_" + Name + ")";
4423 else
4424 Constructor += Name + "(_" + Name + ")";
4425 }
4426 // Initialize all "by ref" arguments.
Chris Lattner5f9e2722011-07-23 10:55:15 +00004427 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Fariborz Jahanian20432ef2010-07-28 23:27:30 +00004428 E = BlockByRefDecls.end(); I != E; ++I) {
4429 std::string Name = (*I)->getNameAsString();
4430 if (firsTime) {
4431 Constructor += " : ";
4432 firsTime = false;
4433 }
4434 else
4435 Constructor += ", ";
Fariborz Jahanian651ba522011-04-01 23:08:13 +00004436 Constructor += Name + "(_" + Name + "->__forwarding)";
Fariborz Jahanian20432ef2010-07-28 23:27:30 +00004437 }
4438
4439 Constructor += " {\n";
Steve Naroff621edce2009-04-29 16:37:50 +00004440 if (GlobalVarDecl)
4441 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4442 else
4443 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff01aec112009-12-06 21:14:13 +00004444 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004445
Steve Naroff01aec112009-12-06 21:14:13 +00004446 Constructor += " Desc = desc;\n";
Steve Naroff54055232008-10-27 17:20:55 +00004447 } else {
4448 // Finish writing the constructor.
Steve Naroff54055232008-10-27 17:20:55 +00004449 Constructor += ", int flags=0) {\n";
Steve Naroff621edce2009-04-29 16:37:50 +00004450 if (GlobalVarDecl)
4451 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4452 else
4453 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff01aec112009-12-06 21:14:13 +00004454 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
4455 Constructor += " Desc = desc;\n";
Steve Naroff54055232008-10-27 17:20:55 +00004456 }
4457 Constructor += " ";
4458 Constructor += "}\n";
4459 S += Constructor;
4460 S += "};\n";
4461 return S;
4462}
4463
Steve Naroff01aec112009-12-06 21:14:13 +00004464std::string RewriteObjC::SynthesizeBlockDescriptor(std::string DescTag,
4465 std::string ImplTag, int i,
Chris Lattner5f9e2722011-07-23 10:55:15 +00004466 StringRef FunName,
Steve Naroff01aec112009-12-06 21:14:13 +00004467 unsigned hasCopy) {
4468 std::string S = "\nstatic struct " + DescTag;
4469
4470 S += " {\n unsigned long reserved;\n";
4471 S += " unsigned long Block_size;\n";
4472 if (hasCopy) {
Fariborz Jahanian4fcc4fd2009-12-21 23:31:42 +00004473 S += " void (*copy)(struct ";
4474 S += ImplTag; S += "*, struct ";
4475 S += ImplTag; S += "*);\n";
4476
4477 S += " void (*dispose)(struct ";
4478 S += ImplTag; S += "*);\n";
Steve Naroff01aec112009-12-06 21:14:13 +00004479 }
4480 S += "} ";
4481
4482 S += DescTag + "_DATA = { 0, sizeof(struct ";
4483 S += ImplTag + ")";
4484 if (hasCopy) {
Daniel Dunbar4087f272010-08-17 22:39:59 +00004485 S += ", __" + FunName.str() + "_block_copy_" + utostr(i);
4486 S += ", __" + FunName.str() + "_block_dispose_" + utostr(i);
Steve Naroff01aec112009-12-06 21:14:13 +00004487 }
4488 S += "};\n";
4489 return S;
4490}
4491
Steve Naroff54055232008-10-27 17:20:55 +00004492void RewriteObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
Chris Lattner5f9e2722011-07-23 10:55:15 +00004493 StringRef FunName) {
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00004494 // Insert declaration for the function in which block literal is used.
Fariborz Jahanianbf070122010-01-15 18:14:52 +00004495 if (CurFunctionDeclToDeclareForBlock && !Blocks.empty())
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00004496 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
Fariborz Jahanian8611eb02010-03-04 21:35:37 +00004497 bool RewriteSC = (GlobalVarDecl &&
4498 !Blocks.empty() &&
John McCalld931b082010-08-26 03:08:43 +00004499 GlobalVarDecl->getStorageClass() == SC_Static &&
Fariborz Jahanian8611eb02010-03-04 21:35:37 +00004500 GlobalVarDecl->getType().getCVRQualifiers());
4501 if (RewriteSC) {
4502 std::string SC(" void __");
4503 SC += GlobalVarDecl->getNameAsString();
4504 SC += "() {}";
4505 InsertText(FunLocStart, SC);
4506 }
4507
Steve Naroff54055232008-10-27 17:20:55 +00004508 // Insert closures that were part of the function.
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004509 for (unsigned i = 0, count=0; i < Blocks.size(); i++) {
4510 CollectBlockDeclRefInfo(Blocks[i]);
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004511 // Need to copy-in the inner copied-in variables not actually used in this
4512 // block.
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004513 for (int j = 0; j < InnerDeclRefsCount[i]; j++) {
4514 BlockDeclRefExpr *Exp = InnerDeclRefs[count++];
4515 ValueDecl *VD = Exp->getDecl();
4516 BlockDeclRefs.push_back(Exp);
4517 if (!Exp->isByRef() && !BlockByCopyDeclsPtrSet.count(VD)) {
4518 BlockByCopyDeclsPtrSet.insert(VD);
4519 BlockByCopyDecls.push_back(VD);
4520 }
4521 if (Exp->isByRef() && !BlockByRefDeclsPtrSet.count(VD)) {
4522 BlockByRefDeclsPtrSet.insert(VD);
4523 BlockByRefDecls.push_back(VD);
4524 }
Fariborz Jahanian92c85682010-10-05 18:05:06 +00004525 // imported objects in the inner blocks not used in the outer
4526 // blocks must be copied/disposed in the outer block as well.
4527 if (Exp->isByRef() ||
4528 VD->getType()->isObjCObjectPointerType() ||
4529 VD->getType()->isBlockPointerType())
4530 ImportedBlockDecls.insert(VD);
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004531 }
Steve Naroff54055232008-10-27 17:20:55 +00004532
Daniel Dunbar4087f272010-08-17 22:39:59 +00004533 std::string ImplTag = "__" + FunName.str() + "_block_impl_" + utostr(i);
4534 std::string DescTag = "__" + FunName.str() + "_block_desc_" + utostr(i);
Mike Stump1eb44332009-09-09 15:08:12 +00004535
Steve Naroff01aec112009-12-06 21:14:13 +00004536 std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
Steve Naroff54055232008-10-27 17:20:55 +00004537
Benjamin Kramerd999b372010-02-14 14:14:16 +00004538 InsertText(FunLocStart, CI);
Steve Naroff54055232008-10-27 17:20:55 +00004539
Steve Naroff01aec112009-12-06 21:14:13 +00004540 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
Mike Stump1eb44332009-09-09 15:08:12 +00004541
Benjamin Kramerd999b372010-02-14 14:14:16 +00004542 InsertText(FunLocStart, CF);
Steve Naroff54055232008-10-27 17:20:55 +00004543
4544 if (ImportedBlockDecls.size()) {
Steve Naroff01aec112009-12-06 21:14:13 +00004545 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
Benjamin Kramerd999b372010-02-14 14:14:16 +00004546 InsertText(FunLocStart, HF);
Steve Naroff54055232008-10-27 17:20:55 +00004547 }
Steve Naroff01aec112009-12-06 21:14:13 +00004548 std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
4549 ImportedBlockDecls.size() > 0);
Benjamin Kramerd999b372010-02-14 14:14:16 +00004550 InsertText(FunLocStart, BD);
Mike Stump1eb44332009-09-09 15:08:12 +00004551
Steve Naroff54055232008-10-27 17:20:55 +00004552 BlockDeclRefs.clear();
4553 BlockByRefDecls.clear();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004554 BlockByRefDeclsPtrSet.clear();
Steve Naroff54055232008-10-27 17:20:55 +00004555 BlockByCopyDecls.clear();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004556 BlockByCopyDeclsPtrSet.clear();
Steve Naroff54055232008-10-27 17:20:55 +00004557 ImportedBlockDecls.clear();
4558 }
Fariborz Jahanian8611eb02010-03-04 21:35:37 +00004559 if (RewriteSC) {
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00004560 // Must insert any 'const/volatile/static here. Since it has been
4561 // removed as result of rewriting of block literals.
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00004562 std::string SC;
John McCalld931b082010-08-26 03:08:43 +00004563 if (GlobalVarDecl->getStorageClass() == SC_Static)
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00004564 SC = "static ";
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00004565 if (GlobalVarDecl->getType().isConstQualified())
4566 SC += "const ";
4567 if (GlobalVarDecl->getType().isVolatileQualified())
4568 SC += "volatile ";
Fariborz Jahanian8611eb02010-03-04 21:35:37 +00004569 if (GlobalVarDecl->getType().isRestrictQualified())
4570 SC += "restrict ";
4571 InsertText(FunLocStart, SC);
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00004572 }
4573
Steve Naroff54055232008-10-27 17:20:55 +00004574 Blocks.clear();
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004575 InnerDeclRefsCount.clear();
4576 InnerDeclRefs.clear();
Steve Naroff54055232008-10-27 17:20:55 +00004577 RewrittenBlockExprs.clear();
4578}
4579
4580void RewriteObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
4581 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
Chris Lattner5f9e2722011-07-23 10:55:15 +00004582 StringRef FuncName = FD->getName();
Mike Stump1eb44332009-09-09 15:08:12 +00004583
Steve Naroff54055232008-10-27 17:20:55 +00004584 SynthesizeBlockLiterals(FunLocStart, FuncName);
4585}
4586
Fariborz Jahaniane61a1d42010-02-10 20:18:25 +00004587static void BuildUniqueMethodName(std::string &Name,
4588 ObjCMethodDecl *MD) {
4589 ObjCInterfaceDecl *IFace = MD->getClassInterface();
Daniel Dunbar4087f272010-08-17 22:39:59 +00004590 Name = IFace->getName();
Fariborz Jahaniane61a1d42010-02-10 20:18:25 +00004591 Name += "__" + MD->getSelector().getAsString();
4592 // Convert colons to underscores.
4593 std::string::size_type loc = 0;
4594 while ((loc = Name.find(":", loc)) != std::string::npos)
4595 Name.replace(loc, 1, "_");
4596}
4597
Steve Naroff54055232008-10-27 17:20:55 +00004598void RewriteObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
Steve Naroffced80a82008-10-30 12:09:33 +00004599 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
4600 //SourceLocation FunLocStart = MD->getLocStart();
Fariborz Jahanian0e1c99a2010-01-29 01:55:49 +00004601 SourceLocation FunLocStart = MD->getLocStart();
Fariborz Jahaniane61a1d42010-02-10 20:18:25 +00004602 std::string FuncName;
4603 BuildUniqueMethodName(FuncName, MD);
Daniel Dunbar4087f272010-08-17 22:39:59 +00004604 SynthesizeBlockLiterals(FunLocStart, FuncName);
Steve Naroff54055232008-10-27 17:20:55 +00004605}
4606
4607void RewriteObjC::GetBlockDeclRefExprs(Stmt *S) {
John McCall7502c1d2011-02-13 04:07:26 +00004608 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroff54055232008-10-27 17:20:55 +00004609 if (*CI) {
4610 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
4611 GetBlockDeclRefExprs(CBE->getBody());
4612 else
4613 GetBlockDeclRefExprs(*CI);
4614 }
4615 // Handle specific things.
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004616 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S)) {
Steve Naroff54055232008-10-27 17:20:55 +00004617 // FIXME: Handle enums.
4618 if (!isa<FunctionDecl>(CDRE->getDecl()))
4619 BlockDeclRefs.push_back(CDRE);
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004620 }
4621 else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S))
4622 if (HasLocalVariableExternalStorage(DRE->getDecl())) {
4623 BlockDeclRefExpr *BDRE =
John McCall6b5a61b2011-02-07 10:33:21 +00004624 new (Context)BlockDeclRefExpr(cast<VarDecl>(DRE->getDecl()),
4625 DRE->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00004626 VK_LValue, DRE->getLocation(), false);
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004627 BlockDeclRefs.push_back(BDRE);
4628 }
4629
Steve Naroff54055232008-10-27 17:20:55 +00004630 return;
4631}
4632
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004633void RewriteObjC::GetInnerBlockDeclRefExprs(Stmt *S,
Chris Lattner5f9e2722011-07-23 10:55:15 +00004634 SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs,
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004635 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts) {
John McCall7502c1d2011-02-13 04:07:26 +00004636 for (Stmt::child_range CI = S->children(); CI; ++CI)
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004637 if (*CI) {
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004638 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI)) {
4639 InnerContexts.insert(cast<DeclContext>(CBE->getBlockDecl()));
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004640 GetInnerBlockDeclRefExprs(CBE->getBody(),
4641 InnerBlockDeclRefs,
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004642 InnerContexts);
4643 }
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004644 else
4645 GetInnerBlockDeclRefExprs(*CI,
4646 InnerBlockDeclRefs,
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004647 InnerContexts);
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004648
4649 }
4650 // Handle specific things.
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004651 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S)) {
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004652 if (!isa<FunctionDecl>(CDRE->getDecl()) &&
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004653 !InnerContexts.count(CDRE->getDecl()->getDeclContext()))
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004654 InnerBlockDeclRefs.push_back(CDRE);
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004655 }
4656 else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4657 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl()))
4658 if (Var->isFunctionOrMethodVarDecl())
4659 ImportedLocalExternalDecls.insert(Var);
4660 }
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004661
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004662 return;
4663}
4664
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004665/// convertFunctionTypeOfBlocks - This routine converts a function type
4666/// whose result type may be a block pointer or whose argument type(s)
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00004667/// might be block pointers to an equivalent function type replacing
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004668/// all block pointers to function pointers.
4669QualType RewriteObjC::convertFunctionTypeOfBlocks(const FunctionType *FT) {
4670 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
4671 // FTP will be null for closures that don't take arguments.
4672 // Generate a funky cast.
Chris Lattner5f9e2722011-07-23 10:55:15 +00004673 SmallVector<QualType, 8> ArgTypes;
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004674 QualType Res = FT->getResultType();
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00004675 bool HasBlockType = convertBlockPointerToFunctionPointer(Res);
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004676
4677 if (FTP) {
4678 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4679 E = FTP->arg_type_end(); I && (I != E); ++I) {
4680 QualType t = *I;
4681 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00004682 if (convertBlockPointerToFunctionPointer(t))
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004683 HasBlockType = true;
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004684 ArgTypes.push_back(t);
4685 }
4686 }
4687 QualType FuncType;
4688 // FIXME. Does this work if block takes no argument but has a return type
4689 // which is of block type?
4690 if (HasBlockType)
John McCalle23cf432010-12-14 08:05:40 +00004691 FuncType = getSimpleFunctionType(Res, &ArgTypes[0], ArgTypes.size());
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004692 else FuncType = QualType(FT, 0);
4693 return FuncType;
4694}
4695
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004696Stmt *RewriteObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
Steve Naroff54055232008-10-27 17:20:55 +00004697 // Navigate to relevant type information.
Steve Naroff54055232008-10-27 17:20:55 +00004698 const BlockPointerType *CPT = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004699
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004700 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004701 CPT = DRE->getType()->getAs<BlockPointerType>();
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004702 } else if (const BlockDeclRefExpr *CDRE =
4703 dyn_cast<BlockDeclRefExpr>(BlockExp)) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004704 CPT = CDRE->getType()->getAs<BlockPointerType>();
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004705 } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004706 CPT = MExpr->getType()->getAs<BlockPointerType>();
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004707 }
4708 else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
4709 return SynthesizeBlockCall(Exp, PRE->getSubExpr());
4710 }
4711 else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
4712 CPT = IEXPR->getType()->getAs<BlockPointerType>();
4713 else if (const ConditionalOperator *CEXPR =
4714 dyn_cast<ConditionalOperator>(BlockExp)) {
4715 Expr *LHSExp = CEXPR->getLHS();
4716 Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
4717 Expr *RHSExp = CEXPR->getRHS();
4718 Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
4719 Expr *CONDExp = CEXPR->getCond();
4720 ConditionalOperator *CondExpr =
4721 new (Context) ConditionalOperator(CONDExp,
4722 SourceLocation(), cast<Expr>(LHSStmt),
Fariborz Jahanianf9b949f2010-08-31 18:02:20 +00004723 SourceLocation(), cast<Expr>(RHSStmt),
John McCall09431682010-11-18 19:01:18 +00004724 Exp->getType(), VK_RValue, OK_Ordinary);
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004725 return CondExpr;
Fariborz Jahaniane24b22b2009-12-18 01:15:21 +00004726 } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
4727 CPT = IRE->getType()->getAs<BlockPointerType>();
John McCall4b9c2d22011-11-06 09:01:30 +00004728 } else if (const PseudoObjectExpr *POE
4729 = dyn_cast<PseudoObjectExpr>(BlockExp)) {
4730 CPT = POE->getType()->castAs<BlockPointerType>();
Steve Naroff54055232008-10-27 17:20:55 +00004731 } else {
4732 assert(1 && "RewriteBlockClass: Bad type");
4733 }
4734 assert(CPT && "RewriteBlockClass: Bad type");
John McCall183700f2009-09-21 23:43:11 +00004735 const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
Steve Naroff54055232008-10-27 17:20:55 +00004736 assert(FT && "RewriteBlockClass: Bad type");
Douglas Gregor72564e72009-02-26 23:50:07 +00004737 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
Steve Naroff54055232008-10-27 17:20:55 +00004738 // FTP will be null for closures that don't take arguments.
Mike Stump1eb44332009-09-09 15:08:12 +00004739
Abramo Bagnara465d41b2010-05-11 21:36:43 +00004740 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004741 SourceLocation(), SourceLocation(),
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004742 &Context->Idents.get("__block_impl"));
4743 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
Steve Naroff54055232008-10-27 17:20:55 +00004744
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004745 // Generate a funky cast.
Chris Lattner5f9e2722011-07-23 10:55:15 +00004746 SmallVector<QualType, 8> ArgTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00004747
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004748 // Push the block argument type.
4749 ArgTypes.push_back(PtrBlock);
Steve Naroff54055232008-10-27 17:20:55 +00004750 if (FTP) {
Mike Stump1eb44332009-09-09 15:08:12 +00004751 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004752 E = FTP->arg_type_end(); I && (I != E); ++I) {
4753 QualType t = *I;
4754 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian8188e5f2010-11-05 18:34:46 +00004755 if (!convertBlockPointerToFunctionPointer(t))
4756 convertToUnqualifiedObjCType(t);
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004757 ArgTypes.push_back(t);
4758 }
Steve Naroff54055232008-10-27 17:20:55 +00004759 }
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004760 // Now do the pointer to function cast.
John McCalle23cf432010-12-14 08:05:40 +00004761 QualType PtrToFuncCastType
4762 = getSimpleFunctionType(Exp->getType(), &ArgTypes[0], ArgTypes.size());
Mike Stump1eb44332009-09-09 15:08:12 +00004763
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004764 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
Mike Stump1eb44332009-09-09 15:08:12 +00004765
John McCall9d125032010-01-15 18:39:57 +00004766 CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
John McCalla5bbc502010-11-15 09:46:46 +00004767 CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00004768 const_cast<Expr*>(BlockExp));
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004769 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00004770 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4771 BlkCast);
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004772 //PE->dump();
Mike Stump1eb44332009-09-09 15:08:12 +00004773
Douglas Gregor44b43212008-12-11 16:49:14 +00004774 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00004775 SourceLocation(),
4776 &Context->Idents.get("FuncPtr"),
4777 Context->VoidPtrTy, 0,
Richard Smith7a614d82011-06-11 17:19:42 +00004778 /*BitWidth=*/0, /*Mutable=*/true,
4779 /*HasInit=*/false);
Ted Kremenek8189cde2009-02-07 01:47:29 +00004780 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
John McCallf89e55a2010-11-18 06:31:45 +00004781 FD->getType(), VK_LValue,
4782 OK_Ordinary);
Mike Stump1eb44332009-09-09 15:08:12 +00004783
Fariborz Jahanian8188e5f2010-11-05 18:34:46 +00004784
John McCall9d125032010-01-15 18:39:57 +00004785 CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
John McCalla5bbc502010-11-15 09:46:46 +00004786 CK_BitCast, ME);
Ted Kremenek8189cde2009-02-07 01:47:29 +00004787 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
Mike Stump1eb44332009-09-09 15:08:12 +00004788
Chris Lattner5f9e2722011-07-23 10:55:15 +00004789 SmallVector<Expr*, 8> BlkExprs;
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004790 // Add the implicit argument.
4791 BlkExprs.push_back(BlkCast);
4792 // Add the user arguments.
Mike Stump1eb44332009-09-09 15:08:12 +00004793 for (CallExpr::arg_iterator I = Exp->arg_begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004794 E = Exp->arg_end(); I != E; ++I) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004795 BlkExprs.push_back(*I);
Steve Naroff54055232008-10-27 17:20:55 +00004796 }
Ted Kremenek668bf912009-02-09 20:51:47 +00004797 CallExpr *CE = new (Context) CallExpr(*Context, PE, &BlkExprs[0],
4798 BlkExprs.size(),
John McCallf89e55a2010-11-18 06:31:45 +00004799 Exp->getType(), VK_RValue,
4800 SourceLocation());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004801 return CE;
Steve Naroff54055232008-10-27 17:20:55 +00004802}
4803
Steve Naroff621edce2009-04-29 16:37:50 +00004804// We need to return the rewritten expression to handle cases where the
4805// BlockDeclRefExpr is embedded in another expression being rewritten.
4806// For example:
4807//
4808// int main() {
4809// __block Foo *f;
4810// __block int i;
Mike Stump1eb44332009-09-09 15:08:12 +00004811//
Steve Naroff621edce2009-04-29 16:37:50 +00004812// void (^myblock)() = ^() {
4813// [f test]; // f is a BlockDeclRefExpr embedded in a message (which is being rewritten).
4814// i = 77;
4815// };
4816//}
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004817Stmt *RewriteObjC::RewriteBlockDeclRefExpr(Expr *DeclRefExp) {
Fariborz Jahanianbbf37e22009-12-23 19:26:34 +00004818 // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004819 // for each DeclRefExp where BYREFVAR is name of the variable.
4820 ValueDecl *VD;
4821 bool isArrow = true;
4822 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(DeclRefExp))
4823 VD = BDRE->getDecl();
4824 else {
4825 VD = cast<DeclRefExpr>(DeclRefExp)->getDecl();
4826 isArrow = false;
4827 }
4828
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004829 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00004830 SourceLocation(),
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004831 &Context->Idents.get("__forwarding"),
4832 Context->VoidPtrTy, 0,
Richard Smith7a614d82011-06-11 17:19:42 +00004833 /*BitWidth=*/0, /*Mutable=*/true,
4834 /*HasInit=*/false);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004835 MemberExpr *ME = new (Context) MemberExpr(DeclRefExp, isArrow,
4836 FD, SourceLocation(),
John McCallf89e55a2010-11-18 06:31:45 +00004837 FD->getType(), VK_LValue,
4838 OK_Ordinary);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004839
Chris Lattner5f9e2722011-07-23 10:55:15 +00004840 StringRef Name = VD->getName();
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00004841 FD = FieldDecl::Create(*Context, 0, SourceLocation(), SourceLocation(),
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004842 &Context->Idents.get(Name),
4843 Context->VoidPtrTy, 0,
Richard Smith7a614d82011-06-11 17:19:42 +00004844 /*BitWidth=*/0, /*Mutable=*/true,
4845 /*HasInit=*/false);
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004846 ME = new (Context) MemberExpr(ME, true, FD, SourceLocation(),
John McCallf89e55a2010-11-18 06:31:45 +00004847 DeclRefExp->getType(), VK_LValue, OK_Ordinary);
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004848
4849
4850
Steve Naroffdf8570d2009-02-02 17:19:26 +00004851 // Need parens to enforce precedence.
Fariborz Jahanian380ee502011-04-01 19:19:28 +00004852 ParenExpr *PE = new (Context) ParenExpr(DeclRefExp->getExprLoc(),
4853 DeclRefExp->getExprLoc(),
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004854 ME);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004855 ReplaceStmt(DeclRefExp, PE);
Steve Naroff621edce2009-04-29 16:37:50 +00004856 return PE;
Steve Naroff54055232008-10-27 17:20:55 +00004857}
4858
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004859// Rewrites the imported local variable V with external storage
4860// (static, extern, etc.) as *V
4861//
4862Stmt *RewriteObjC::RewriteLocalVariableExternalStorage(DeclRefExpr *DRE) {
4863 ValueDecl *VD = DRE->getDecl();
4864 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4865 if (!ImportedLocalExternalDecls.count(Var))
4866 return DRE;
John McCallf89e55a2010-11-18 06:31:45 +00004867 Expr *Exp = new (Context) UnaryOperator(DRE, UO_Deref, DRE->getType(),
4868 VK_LValue, OK_Ordinary,
4869 DRE->getLocation());
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004870 // Need parens to enforce precedence.
4871 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4872 Exp);
4873 ReplaceStmt(DRE, PE);
4874 return PE;
4875}
4876
Steve Naroffb2f9e512008-11-03 23:29:32 +00004877void RewriteObjC::RewriteCastExpr(CStyleCastExpr *CE) {
4878 SourceLocation LocStart = CE->getLParenLoc();
4879 SourceLocation LocEnd = CE->getRParenLoc();
Steve Narofffa15fd92008-10-28 20:29:00 +00004880
4881 // Need to avoid trying to rewrite synthesized casts.
4882 if (LocStart.isInvalid())
4883 return;
Steve Naroff8f6ce572008-11-03 11:20:24 +00004884 // Need to avoid trying to rewrite casts contained in macros.
4885 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
4886 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004887
Steve Naroff54055232008-10-27 17:20:55 +00004888 const char *startBuf = SM->getCharacterData(LocStart);
4889 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahanian1d4fca22010-01-19 21:48:35 +00004890 QualType QT = CE->getType();
4891 const Type* TypePtr = QT->getAs<Type>();
4892 if (isa<TypeOfExprType>(TypePtr)) {
4893 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
4894 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
4895 std::string TypeAsString = "(";
Fariborz Jahanianafad76f2010-02-18 01:20:22 +00004896 RewriteBlockPointerType(TypeAsString, QT);
Fariborz Jahanian1d4fca22010-01-19 21:48:35 +00004897 TypeAsString += ")";
Benjamin Kramerd999b372010-02-14 14:14:16 +00004898 ReplaceText(LocStart, endBuf-startBuf+1, TypeAsString);
Fariborz Jahanian1d4fca22010-01-19 21:48:35 +00004899 return;
4900 }
Steve Naroff54055232008-10-27 17:20:55 +00004901 // advance the location to startArgList.
4902 const char *argPtr = startBuf;
Mike Stump1eb44332009-09-09 15:08:12 +00004903
Steve Naroff54055232008-10-27 17:20:55 +00004904 while (*argPtr++ && (argPtr < endBuf)) {
4905 switch (*argPtr) {
Mike Stumpb7166332010-01-20 02:03:14 +00004906 case '^':
4907 // Replace the '^' with '*'.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00004908 LocStart = LocStart.getLocWithOffset(argPtr-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00004909 ReplaceText(LocStart, 1, "*");
Mike Stumpb7166332010-01-20 02:03:14 +00004910 break;
Steve Naroff54055232008-10-27 17:20:55 +00004911 }
4912 }
4913 return;
4914}
4915
4916void RewriteObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
4917 SourceLocation DeclLoc = FD->getLocation();
4918 unsigned parenCount = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004919
Steve Naroff54055232008-10-27 17:20:55 +00004920 // We have 1 or more arguments that have closure pointers.
4921 const char *startBuf = SM->getCharacterData(DeclLoc);
4922 const char *startArgList = strchr(startBuf, '(');
Mike Stump1eb44332009-09-09 15:08:12 +00004923
Steve Naroff54055232008-10-27 17:20:55 +00004924 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
Mike Stump1eb44332009-09-09 15:08:12 +00004925
Steve Naroff54055232008-10-27 17:20:55 +00004926 parenCount++;
4927 // advance the location to startArgList.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00004928 DeclLoc = DeclLoc.getLocWithOffset(startArgList-startBuf);
Steve Naroff54055232008-10-27 17:20:55 +00004929 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
Mike Stump1eb44332009-09-09 15:08:12 +00004930
Steve Naroff54055232008-10-27 17:20:55 +00004931 const char *argPtr = startArgList;
Mike Stump1eb44332009-09-09 15:08:12 +00004932
Steve Naroff54055232008-10-27 17:20:55 +00004933 while (*argPtr++ && parenCount) {
4934 switch (*argPtr) {
Mike Stumpb7166332010-01-20 02:03:14 +00004935 case '^':
4936 // Replace the '^' with '*'.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00004937 DeclLoc = DeclLoc.getLocWithOffset(argPtr-startArgList);
Benjamin Kramerd999b372010-02-14 14:14:16 +00004938 ReplaceText(DeclLoc, 1, "*");
Mike Stumpb7166332010-01-20 02:03:14 +00004939 break;
4940 case '(':
4941 parenCount++;
4942 break;
4943 case ')':
4944 parenCount--;
4945 break;
Steve Naroff54055232008-10-27 17:20:55 +00004946 }
4947 }
4948 return;
4949}
4950
4951bool RewriteObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
Douglas Gregor72564e72009-02-26 23:50:07 +00004952 const FunctionProtoType *FTP;
Ted Kremenek6217b802009-07-29 21:53:49 +00004953 const PointerType *PT = QT->getAs<PointerType>();
Steve Naroff54055232008-10-27 17:20:55 +00004954 if (PT) {
John McCall183700f2009-09-21 23:43:11 +00004955 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff54055232008-10-27 17:20:55 +00004956 } else {
Ted Kremenek6217b802009-07-29 21:53:49 +00004957 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
Steve Naroff54055232008-10-27 17:20:55 +00004958 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
John McCall183700f2009-09-21 23:43:11 +00004959 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff54055232008-10-27 17:20:55 +00004960 }
4961 if (FTP) {
Mike Stump1eb44332009-09-09 15:08:12 +00004962 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004963 E = FTP->arg_type_end(); I != E; ++I)
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004964 if (isTopLevelBlockPointerType(*I))
Steve Naroff54055232008-10-27 17:20:55 +00004965 return true;
4966 }
4967 return false;
4968}
4969
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004970bool RewriteObjC::PointerTypeTakesAnyObjCQualifiedType(QualType QT) {
4971 const FunctionProtoType *FTP;
4972 const PointerType *PT = QT->getAs<PointerType>();
4973 if (PT) {
4974 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4975 } else {
4976 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4977 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4978 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4979 }
4980 if (FTP) {
4981 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Fariborz Jahanian06de2cf2010-11-03 23:50:34 +00004982 E = FTP->arg_type_end(); I != E; ++I) {
4983 if ((*I)->isObjCQualifiedIdType())
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004984 return true;
Fariborz Jahanian06de2cf2010-11-03 23:50:34 +00004985 if ((*I)->isObjCObjectPointerType() &&
4986 (*I)->getPointeeType()->isObjCQualifiedInterfaceType())
4987 return true;
4988 }
4989
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004990 }
4991 return false;
4992}
4993
Ted Kremenek8189cde2009-02-07 01:47:29 +00004994void RewriteObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
4995 const char *&RParen) {
Steve Naroff54055232008-10-27 17:20:55 +00004996 const char *argPtr = strchr(Name, '(');
4997 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
Mike Stump1eb44332009-09-09 15:08:12 +00004998
Steve Naroff54055232008-10-27 17:20:55 +00004999 LParen = argPtr; // output the start.
5000 argPtr++; // skip past the left paren.
5001 unsigned parenCount = 1;
Mike Stump1eb44332009-09-09 15:08:12 +00005002
Steve Naroff54055232008-10-27 17:20:55 +00005003 while (*argPtr && parenCount) {
5004 switch (*argPtr) {
Mike Stumpb7166332010-01-20 02:03:14 +00005005 case '(': parenCount++; break;
5006 case ')': parenCount--; break;
5007 default: break;
Steve Naroff54055232008-10-27 17:20:55 +00005008 }
5009 if (parenCount) argPtr++;
5010 }
5011 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
5012 RParen = argPtr; // output the end
5013}
5014
5015void RewriteObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
5016 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
5017 RewriteBlockPointerFunctionArgs(FD);
5018 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005019 }
Steve Naroff54055232008-10-27 17:20:55 +00005020 // Handle Variables and Typedefs.
5021 SourceLocation DeclLoc = ND->getLocation();
5022 QualType DeclT;
5023 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
5024 DeclT = VD->getType();
Richard Smith162e1c12011-04-15 14:24:37 +00005025 else if (TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(ND))
Steve Naroff54055232008-10-27 17:20:55 +00005026 DeclT = TDD->getUnderlyingType();
5027 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
5028 DeclT = FD->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00005029 else
David Blaikieb219cfc2011-09-23 05:06:16 +00005030 llvm_unreachable("RewriteBlockPointerDecl(): Decl type not yet handled");
Mike Stump1eb44332009-09-09 15:08:12 +00005031
Steve Naroff54055232008-10-27 17:20:55 +00005032 const char *startBuf = SM->getCharacterData(DeclLoc);
5033 const char *endBuf = startBuf;
5034 // scan backward (from the decl location) for the end of the previous decl.
5035 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
5036 startBuf--;
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00005037 SourceLocation Start = DeclLoc.getLocWithOffset(startBuf-endBuf);
Fariborz Jahaniane985d012010-11-03 23:29:24 +00005038 std::string buf;
5039 unsigned OrigLength=0;
Steve Naroff54055232008-10-27 17:20:55 +00005040 // *startBuf != '^' if we are dealing with a pointer to function that
5041 // may take block argument types (which will be handled below).
5042 if (*startBuf == '^') {
5043 // Replace the '^' with '*', computing a negative offset.
Fariborz Jahaniane985d012010-11-03 23:29:24 +00005044 buf = '*';
5045 startBuf++;
5046 OrigLength++;
Steve Naroff54055232008-10-27 17:20:55 +00005047 }
Fariborz Jahaniane985d012010-11-03 23:29:24 +00005048 while (*startBuf != ')') {
5049 buf += *startBuf;
5050 startBuf++;
5051 OrigLength++;
5052 }
5053 buf += ')';
5054 OrigLength++;
5055
5056 if (PointerTypeTakesAnyBlockArguments(DeclT) ||
5057 PointerTypeTakesAnyObjCQualifiedType(DeclT)) {
Steve Naroff54055232008-10-27 17:20:55 +00005058 // Replace the '^' with '*' for arguments.
Fariborz Jahaniane985d012010-11-03 23:29:24 +00005059 // Replace id<P> with id/*<>*/
Steve Naroff54055232008-10-27 17:20:55 +00005060 DeclLoc = ND->getLocation();
5061 startBuf = SM->getCharacterData(DeclLoc);
5062 const char *argListBegin, *argListEnd;
5063 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
5064 while (argListBegin < argListEnd) {
Fariborz Jahaniane985d012010-11-03 23:29:24 +00005065 if (*argListBegin == '^')
5066 buf += '*';
5067 else if (*argListBegin == '<') {
5068 buf += "/*";
5069 buf += *argListBegin++;
5070 OrigLength++;;
5071 while (*argListBegin != '>') {
5072 buf += *argListBegin++;
5073 OrigLength++;
5074 }
5075 buf += *argListBegin;
5076 buf += "*/";
Steve Naroff54055232008-10-27 17:20:55 +00005077 }
Fariborz Jahaniane985d012010-11-03 23:29:24 +00005078 else
5079 buf += *argListBegin;
Steve Naroff54055232008-10-27 17:20:55 +00005080 argListBegin++;
Fariborz Jahaniane985d012010-11-03 23:29:24 +00005081 OrigLength++;
Steve Naroff54055232008-10-27 17:20:55 +00005082 }
Fariborz Jahaniane985d012010-11-03 23:29:24 +00005083 buf += ')';
5084 OrigLength++;
Steve Naroff54055232008-10-27 17:20:55 +00005085 }
Fariborz Jahaniane985d012010-11-03 23:29:24 +00005086 ReplaceText(Start, OrigLength, buf);
5087
Steve Naroff54055232008-10-27 17:20:55 +00005088 return;
5089}
5090
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005091
5092/// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
5093/// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
5094/// struct Block_byref_id_object *src) {
5095/// _Block_object_assign (&_dest->object, _src->object,
5096/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
5097/// [|BLOCK_FIELD_IS_WEAK]) // object
5098/// _Block_object_assign(&_dest->object, _src->object,
5099/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
5100/// [|BLOCK_FIELD_IS_WEAK]) // block
5101/// }
5102/// And:
5103/// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
5104/// _Block_object_dispose(_src->object,
5105/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
5106/// [|BLOCK_FIELD_IS_WEAK]) // object
5107/// _Block_object_dispose(_src->object,
5108/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
5109/// [|BLOCK_FIELD_IS_WEAK]) // block
5110/// }
5111
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005112std::string RewriteObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
5113 int flag) {
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005114 std::string S;
Benjamin Kramer1211a712010-01-10 19:57:50 +00005115 if (CopyDestroyCache.count(flag))
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005116 return S;
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005117 CopyDestroyCache.insert(flag);
5118 S = "static void __Block_byref_id_object_copy_";
5119 S += utostr(flag);
5120 S += "(void *dst, void *src) {\n";
5121
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005122 // offset into the object pointer is computed as:
5123 // void * + void* + int + int + void* + void *
5124 unsigned IntSize =
5125 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
5126 unsigned VoidPtrSize =
5127 static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
5128
Ken Dyck0c4e5d62011-04-30 16:08:27 +00005129 unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/Context->getCharWidth();
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005130 S += " _Block_object_assign((char*)dst + ";
5131 S += utostr(offset);
5132 S += ", *(void * *) ((char*)src + ";
5133 S += utostr(offset);
5134 S += "), ";
5135 S += utostr(flag);
5136 S += ");\n}\n";
5137
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005138 S += "static void __Block_byref_id_object_dispose_";
5139 S += utostr(flag);
5140 S += "(void *src) {\n";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005141 S += " _Block_object_dispose(*(void * *) ((char*)src + ";
5142 S += utostr(offset);
5143 S += "), ";
5144 S += utostr(flag);
5145 S += ");\n}\n";
5146 return S;
5147}
5148
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005149/// RewriteByRefVar - For each __block typex ND variable this routine transforms
5150/// the declaration into:
5151/// struct __Block_byref_ND {
5152/// void *__isa; // NULL for everything except __weak pointers
5153/// struct __Block_byref_ND *__forwarding;
5154/// int32_t __flags;
5155/// int32_t __size;
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005156/// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
5157/// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005158/// typex ND;
5159/// };
5160///
5161/// It then replaces declaration of ND variable with:
5162/// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
5163/// __size=sizeof(struct __Block_byref_ND),
5164/// ND=initializer-if-any};
5165///
5166///
5167void RewriteObjC::RewriteByRefVar(VarDecl *ND) {
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00005168 // Insert declaration for the function in which block literal is
5169 // used.
5170 if (CurFunctionDeclToDeclareForBlock)
5171 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
Fariborz Jahanian2086d542010-01-05 19:21:35 +00005172 int flag = 0;
5173 int isa = 0;
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005174 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
Fariborz Jahaniand64a4f42010-02-26 22:49:11 +00005175 if (DeclLoc.isInvalid())
5176 // If type location is missing, it is because of missing type (a warning).
5177 // Use variable's location which is good for this case.
5178 DeclLoc = ND->getLocation();
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005179 const char *startBuf = SM->getCharacterData(DeclLoc);
Fariborz Jahanian6f0a0a92009-12-30 20:38:08 +00005180 SourceLocation X = ND->getLocEnd();
Chandler Carruth40278532011-07-25 16:49:02 +00005181 X = SM->getExpansionLoc(X);
Fariborz Jahanian6f0a0a92009-12-30 20:38:08 +00005182 const char *endBuf = SM->getCharacterData(X);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005183 std::string Name(ND->getNameAsString());
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005184 std::string ByrefType;
Fariborz Jahanian1e8011e2011-01-27 23:18:15 +00005185 RewriteByRefString(ByrefType, Name, ND, true);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005186 ByrefType += " {\n";
5187 ByrefType += " void *__isa;\n";
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005188 RewriteByRefString(ByrefType, Name, ND);
5189 ByrefType += " *__forwarding;\n";
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005190 ByrefType += " int __flags;\n";
5191 ByrefType += " int __size;\n";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005192 // Add void *__Block_byref_id_object_copy;
5193 // void *__Block_byref_id_object_dispose; if needed.
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00005194 QualType Ty = ND->getType();
5195 bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty);
5196 if (HasCopyAndDispose) {
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005197 ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
5198 ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00005199 }
Fariborz Jahanian822ac872011-03-31 22:49:32 +00005200
5201 QualType T = Ty;
5202 (void)convertBlockPointerToFunctionPointer(T);
Douglas Gregor30c42402011-09-27 22:38:19 +00005203 T.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahanian822ac872011-03-31 22:49:32 +00005204
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005205 ByrefType += " " + Name + ";\n";
5206 ByrefType += "};\n";
5207 // Insert this type in global scope. It is needed by helper function.
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00005208 SourceLocation FunLocStart;
5209 if (CurFunctionDef)
5210 FunLocStart = CurFunctionDef->getTypeSpecStartLoc();
5211 else {
5212 assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null");
5213 FunLocStart = CurMethodDef->getLocStart();
5214 }
Benjamin Kramerd999b372010-02-14 14:14:16 +00005215 InsertText(FunLocStart, ByrefType);
Fariborz Jahanian2086d542010-01-05 19:21:35 +00005216 if (Ty.isObjCGCWeak()) {
5217 flag |= BLOCK_FIELD_IS_WEAK;
5218 isa = 1;
5219 }
5220
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005221 if (HasCopyAndDispose) {
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005222 flag = BLOCK_BYREF_CALLER;
5223 QualType Ty = ND->getType();
5224 // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
5225 if (Ty->isBlockPointerType())
5226 flag |= BLOCK_FIELD_IS_BLOCK;
5227 else
5228 flag |= BLOCK_FIELD_IS_OBJECT;
5229 std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005230 if (!HF.empty())
Benjamin Kramerd999b372010-02-14 14:14:16 +00005231 InsertText(FunLocStart, HF);
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005232 }
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005233
5234 // struct __Block_byref_ND ND =
5235 // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
5236 // initializer-if-any};
5237 bool hasInit = (ND->getInit() != 0);
Fariborz Jahaniane1f84f82010-01-05 18:15:57 +00005238 unsigned flags = 0;
5239 if (HasCopyAndDispose)
5240 flags |= BLOCK_HAS_COPY_DISPOSE;
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005241 Name = ND->getNameAsString();
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005242 ByrefType.clear();
5243 RewriteByRefString(ByrefType, Name, ND);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00005244 std::string ForwardingCastType("(");
5245 ForwardingCastType += ByrefType + " *)";
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005246 if (!hasInit) {
Fariborz Jahanian2086d542010-01-05 19:21:35 +00005247 ByrefType += " " + Name + " = {(void*)";
5248 ByrefType += utostr(isa);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00005249 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005250 ByrefType += utostr(flags);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00005251 ByrefType += ", ";
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005252 ByrefType += "sizeof(";
5253 RewriteByRefString(ByrefType, Name, ND);
5254 ByrefType += ")";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005255 if (HasCopyAndDispose) {
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005256 ByrefType += ", __Block_byref_id_object_copy_";
5257 ByrefType += utostr(flag);
5258 ByrefType += ", __Block_byref_id_object_dispose_";
5259 ByrefType += utostr(flag);
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005260 }
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005261 ByrefType += "};\n";
Fariborz Jahanian822ac872011-03-31 22:49:32 +00005262 unsigned nameSize = Name.size();
5263 // for block or function pointer declaration. Name is aleady
5264 // part of the declaration.
5265 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType())
5266 nameSize = 1;
5267 ReplaceText(DeclLoc, endBuf-startBuf+nameSize, ByrefType);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005268 }
5269 else {
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00005270 SourceLocation startLoc;
5271 Expr *E = ND->getInit();
5272 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
5273 startLoc = ECE->getLParenLoc();
5274 else
5275 startLoc = E->getLocStart();
Chandler Carruth40278532011-07-25 16:49:02 +00005276 startLoc = SM->getExpansionLoc(startLoc);
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00005277 endBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005278 ByrefType += " " + Name;
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00005279 ByrefType += " = {(void*)";
Fariborz Jahanian2086d542010-01-05 19:21:35 +00005280 ByrefType += utostr(isa);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00005281 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005282 ByrefType += utostr(flags);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00005283 ByrefType += ", ";
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005284 ByrefType += "sizeof(";
5285 RewriteByRefString(ByrefType, Name, ND);
5286 ByrefType += "), ";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005287 if (HasCopyAndDispose) {
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005288 ByrefType += "__Block_byref_id_object_copy_";
5289 ByrefType += utostr(flag);
5290 ByrefType += ", __Block_byref_id_object_dispose_";
5291 ByrefType += utostr(flag);
5292 ByrefType += ", ";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005293 }
Benjamin Kramerd999b372010-02-14 14:14:16 +00005294 ReplaceText(DeclLoc, endBuf-startBuf, ByrefType);
Steve Naroffc5143c52009-12-23 17:24:33 +00005295
5296 // Complete the newly synthesized compound expression by inserting a right
5297 // curly brace before the end of the declaration.
5298 // FIXME: This approach avoids rewriting the initializer expression. It
5299 // also assumes there is only one declarator. For example, the following
5300 // isn't currently supported by this routine (in general):
5301 //
5302 // double __block BYREFVAR = 1.34, BYREFVAR2 = 1.37;
5303 //
Fariborz Jahanian5f371ee2010-07-21 17:36:39 +00005304 const char *startInitializerBuf = SM->getCharacterData(startLoc);
5305 const char *semiBuf = strchr(startInitializerBuf, ';');
Steve Naroffc5143c52009-12-23 17:24:33 +00005306 assert((*semiBuf == ';') && "RewriteByRefVar: can't find ';'");
5307 SourceLocation semiLoc =
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00005308 startLoc.getLocWithOffset(semiBuf-startInitializerBuf);
Steve Naroffc5143c52009-12-23 17:24:33 +00005309
Benjamin Kramerd999b372010-02-14 14:14:16 +00005310 InsertText(semiLoc, "}");
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005311 }
Fariborz Jahanian1be6b462009-12-22 00:48:54 +00005312 return;
5313}
5314
Mike Stump1eb44332009-09-09 15:08:12 +00005315void RewriteObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
Steve Naroff54055232008-10-27 17:20:55 +00005316 // Add initializers for any closure decl refs.
5317 GetBlockDeclRefExprs(Exp->getBody());
5318 if (BlockDeclRefs.size()) {
5319 // Unique all "by copy" declarations.
5320 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
Fariborz Jahanianbab71682010-02-11 23:35:57 +00005321 if (!BlockDeclRefs[i]->isByRef()) {
5322 if (!BlockByCopyDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5323 BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5324 BlockByCopyDecls.push_back(BlockDeclRefs[i]->getDecl());
5325 }
5326 }
Steve Naroff54055232008-10-27 17:20:55 +00005327 // Unique all "by ref" declarations.
5328 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
5329 if (BlockDeclRefs[i]->isByRef()) {
Fariborz Jahanianbab71682010-02-11 23:35:57 +00005330 if (!BlockByRefDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5331 BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5332 BlockByRefDecls.push_back(BlockDeclRefs[i]->getDecl());
5333 }
Steve Naroff54055232008-10-27 17:20:55 +00005334 }
5335 // Find any imported blocks...they will need special attention.
5336 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
Fariborz Jahanian4fcc4fd2009-12-21 23:31:42 +00005337 if (BlockDeclRefs[i]->isByRef() ||
5338 BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
Fariborz Jahanian5b011b02010-02-26 21:46:27 +00005339 BlockDeclRefs[i]->getType()->isBlockPointerType())
Steve Naroff54055232008-10-27 17:20:55 +00005340 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
Steve Naroff54055232008-10-27 17:20:55 +00005341 }
5342}
5343
Chris Lattner5f9e2722011-07-23 10:55:15 +00005344FunctionDecl *RewriteObjC::SynthBlockInitFunctionDecl(StringRef name) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005345 IdentifierInfo *ID = &Context->Idents.get(name);
Douglas Gregor72564e72009-02-26 23:50:07 +00005346 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00005347 return FunctionDecl::Create(*Context, TUDecl, SourceLocation(),
5348 SourceLocation(), ID, FType, 0, SC_Extern,
John McCalld931b082010-08-26 03:08:43 +00005349 SC_None, false, false);
Steve Narofffa15fd92008-10-28 20:29:00 +00005350}
5351
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005352Stmt *RewriteObjC::SynthBlockInitExpr(BlockExpr *Exp,
Chris Lattner5f9e2722011-07-23 10:55:15 +00005353 const SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs) {
Fariborz Jahanian05318d82011-02-16 22:37:10 +00005354 const BlockDecl *block = Exp->getBlockDecl();
Steve Narofffa15fd92008-10-28 20:29:00 +00005355 Blocks.push_back(Exp);
5356
5357 CollectBlockDeclRefInfo(Exp);
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005358
5359 // Add inner imported variables now used in current block.
5360 int countOfInnerDecls = 0;
Fariborz Jahanian1276bfe2010-02-26 22:36:30 +00005361 if (!InnerBlockDeclRefs.empty()) {
5362 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++) {
5363 BlockDeclRefExpr *Exp = InnerBlockDeclRefs[i];
5364 ValueDecl *VD = Exp->getDecl();
5365 if (!Exp->isByRef() && !BlockByCopyDeclsPtrSet.count(VD)) {
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005366 // We need to save the copied-in variables in nested
5367 // blocks because it is needed at the end for some of the API generations.
5368 // See SynthesizeBlockLiterals routine.
Fariborz Jahanian1276bfe2010-02-26 22:36:30 +00005369 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5370 BlockDeclRefs.push_back(Exp);
5371 BlockByCopyDeclsPtrSet.insert(VD);
5372 BlockByCopyDecls.push_back(VD);
5373 }
5374 if (Exp->isByRef() && !BlockByRefDeclsPtrSet.count(VD)) {
5375 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5376 BlockDeclRefs.push_back(Exp);
5377 BlockByRefDeclsPtrSet.insert(VD);
5378 BlockByRefDecls.push_back(VD);
5379 }
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005380 }
Fariborz Jahanian1276bfe2010-02-26 22:36:30 +00005381 // Find any imported blocks...they will need special attention.
5382 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++)
5383 if (InnerBlockDeclRefs[i]->isByRef() ||
5384 InnerBlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
5385 InnerBlockDeclRefs[i]->getType()->isBlockPointerType())
5386 ImportedBlockDecls.insert(InnerBlockDeclRefs[i]->getDecl());
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005387 }
5388 InnerDeclRefsCount.push_back(countOfInnerDecls);
5389
Steve Narofffa15fd92008-10-28 20:29:00 +00005390 std::string FuncName;
Mike Stump1eb44332009-09-09 15:08:12 +00005391
Steve Narofffa15fd92008-10-28 20:29:00 +00005392 if (CurFunctionDef)
Chris Lattner077bf5e2008-11-24 03:33:13 +00005393 FuncName = CurFunctionDef->getNameAsString();
Fariborz Jahaniane61a1d42010-02-10 20:18:25 +00005394 else if (CurMethodDef)
5395 BuildUniqueMethodName(FuncName, CurMethodDef);
5396 else if (GlobalVarDecl)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00005397 FuncName = std::string(GlobalVarDecl->getNameAsString());
Mike Stump1eb44332009-09-09 15:08:12 +00005398
Steve Narofffa15fd92008-10-28 20:29:00 +00005399 std::string BlockNumber = utostr(Blocks.size()-1);
Mike Stump1eb44332009-09-09 15:08:12 +00005400
Steve Narofffa15fd92008-10-28 20:29:00 +00005401 std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber;
5402 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
Mike Stump1eb44332009-09-09 15:08:12 +00005403
Steve Narofffa15fd92008-10-28 20:29:00 +00005404 // Get a pointer to the function type so we can cast appropriately.
Fariborz Jahanian1f906222010-05-25 15:56:08 +00005405 QualType BFT = convertFunctionTypeOfBlocks(Exp->getFunctionType());
5406 QualType FType = Context->getPointerType(BFT);
Steve Narofffa15fd92008-10-28 20:29:00 +00005407
5408 FunctionDecl *FD;
5409 Expr *NewRep;
Mike Stump1eb44332009-09-09 15:08:12 +00005410
Steve Narofffa15fd92008-10-28 20:29:00 +00005411 // Simulate a contructor call...
Daniel Dunbar4087f272010-08-17 22:39:59 +00005412 FD = SynthBlockInitFunctionDecl(Tag);
John McCallf89e55a2010-11-18 06:31:45 +00005413 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, FType, VK_RValue,
5414 SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00005415
Chris Lattner5f9e2722011-07-23 10:55:15 +00005416 SmallVector<Expr*, 4> InitExprs;
Mike Stump1eb44332009-09-09 15:08:12 +00005417
Steve Narofffdc03722008-10-29 21:23:59 +00005418 // Initialize the block function.
Daniel Dunbar4087f272010-08-17 22:39:59 +00005419 FD = SynthBlockInitFunctionDecl(Func);
John McCallf89e55a2010-11-18 06:31:45 +00005420 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
Ted Kremenek8189cde2009-02-07 01:47:29 +00005421 SourceLocation());
John McCall9d125032010-01-15 18:39:57 +00005422 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
John McCalla5bbc502010-11-15 09:46:46 +00005423 CK_BitCast, Arg);
Mike Stump1eb44332009-09-09 15:08:12 +00005424 InitExprs.push_back(castExpr);
5425
Steve Naroff01aec112009-12-06 21:14:13 +00005426 // Initialize the block descriptor.
5427 std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
Mike Stump1eb44332009-09-09 15:08:12 +00005428
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00005429 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl,
5430 SourceLocation(), SourceLocation(),
5431 &Context->Idents.get(DescData.c_str()),
5432 Context->VoidPtrTy, 0,
5433 SC_Static, SC_None);
John McCallf89e55a2010-11-18 06:31:45 +00005434 UnaryOperator *DescRefExpr =
5435 new (Context) UnaryOperator(new (Context) DeclRefExpr(NewVD,
5436 Context->VoidPtrTy,
5437 VK_LValue,
5438 SourceLocation()),
5439 UO_AddrOf,
5440 Context->getPointerType(Context->VoidPtrTy),
5441 VK_RValue, OK_Ordinary,
5442 SourceLocation());
Steve Naroff01aec112009-12-06 21:14:13 +00005443 InitExprs.push_back(DescRefExpr);
5444
Steve Narofffa15fd92008-10-28 20:29:00 +00005445 // Add initializers for any closure decl refs.
5446 if (BlockDeclRefs.size()) {
Steve Narofffdc03722008-10-29 21:23:59 +00005447 Expr *Exp;
Steve Narofffa15fd92008-10-28 20:29:00 +00005448 // Output all "by copy" declarations.
Chris Lattner5f9e2722011-07-23 10:55:15 +00005449 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Narofffa15fd92008-10-28 20:29:00 +00005450 E = BlockByCopyDecls.end(); I != E; ++I) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005451 if (isObjCType((*I)->getType())) {
Steve Narofffdc03722008-10-29 21:23:59 +00005452 // FIXME: Conform to ABI ([[obj retain] autorelease]).
Daniel Dunbar4087f272010-08-17 22:39:59 +00005453 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf89e55a2010-11-18 06:31:45 +00005454 Exp = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
5455 SourceLocation());
Fariborz Jahaniana5a79872010-05-24 18:32:56 +00005456 if (HasLocalVariableExternalStorage(*I)) {
5457 QualType QT = (*I)->getType();
5458 QT = Context->getPointerType(QT);
John McCallf89e55a2010-11-18 06:31:45 +00005459 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
5460 OK_Ordinary, SourceLocation());
Fariborz Jahaniana5a79872010-05-24 18:32:56 +00005461 }
Steve Naroff01f2ffa2008-12-11 21:05:33 +00005462 } else if (isTopLevelBlockPointerType((*I)->getType())) {
Daniel Dunbar4087f272010-08-17 22:39:59 +00005463 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf89e55a2010-11-18 06:31:45 +00005464 Arg = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
5465 SourceLocation());
John McCall9d125032010-01-15 18:39:57 +00005466 Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
John McCalla5bbc502010-11-15 09:46:46 +00005467 CK_BitCast, Arg);
Steve Narofffa15fd92008-10-28 20:29:00 +00005468 } else {
Daniel Dunbar4087f272010-08-17 22:39:59 +00005469 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf89e55a2010-11-18 06:31:45 +00005470 Exp = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
5471 SourceLocation());
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00005472 if (HasLocalVariableExternalStorage(*I)) {
5473 QualType QT = (*I)->getType();
5474 QT = Context->getPointerType(QT);
John McCallf89e55a2010-11-18 06:31:45 +00005475 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
5476 OK_Ordinary, SourceLocation());
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00005477 }
5478
Steve Narofffa15fd92008-10-28 20:29:00 +00005479 }
Mike Stump1eb44332009-09-09 15:08:12 +00005480 InitExprs.push_back(Exp);
Steve Narofffa15fd92008-10-28 20:29:00 +00005481 }
5482 // Output all "by ref" declarations.
Chris Lattner5f9e2722011-07-23 10:55:15 +00005483 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Narofffa15fd92008-10-28 20:29:00 +00005484 E = BlockByRefDecls.end(); I != E; ++I) {
Fariborz Jahanian2663f522010-02-04 00:07:58 +00005485 ValueDecl *ND = (*I);
5486 std::string Name(ND->getNameAsString());
5487 std::string RecName;
Fariborz Jahanian1e8011e2011-01-27 23:18:15 +00005488 RewriteByRefString(RecName, Name, ND, true);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00005489 IdentifierInfo *II = &Context->Idents.get(RecName.c_str()
5490 + sizeof("struct"));
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005491 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00005492 SourceLocation(), SourceLocation(),
5493 II);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00005494 assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl");
5495 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
5496
Daniel Dunbar4087f272010-08-17 22:39:59 +00005497 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf89e55a2010-11-18 06:31:45 +00005498 Exp = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
5499 SourceLocation());
Fariborz Jahanian05318d82011-02-16 22:37:10 +00005500 bool isNestedCapturedVar = false;
5501 if (block)
5502 for (BlockDecl::capture_const_iterator ci = block->capture_begin(),
5503 ce = block->capture_end(); ci != ce; ++ci) {
5504 const VarDecl *variable = ci->getVariable();
5505 if (variable == ND && ci->isNested()) {
5506 assert (ci->isByRef() &&
5507 "SynthBlockInitExpr - captured block variable is not byref");
5508 isNestedCapturedVar = true;
5509 break;
5510 }
5511 }
5512 // captured nested byref variable has its address passed. Do not take
5513 // its address again.
5514 if (!isNestedCapturedVar)
5515 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf,
John McCallf89e55a2010-11-18 06:31:45 +00005516 Context->getPointerType(Exp->getType()),
5517 VK_RValue, OK_Ordinary, SourceLocation());
John McCalla5bbc502010-11-15 09:46:46 +00005518 Exp = NoTypeInfoCStyleCastExpr(Context, castT, CK_BitCast, Exp);
Mike Stump1eb44332009-09-09 15:08:12 +00005519 InitExprs.push_back(Exp);
Steve Narofffa15fd92008-10-28 20:29:00 +00005520 }
5521 }
Fariborz Jahanianff127882009-12-23 21:52:32 +00005522 if (ImportedBlockDecls.size()) {
5523 // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
5524 int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
Steve Naroff01aec112009-12-06 21:14:13 +00005525 unsigned IntSize =
5526 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00005527 Expr *FlagExp = IntegerLiteral::Create(*Context, llvm::APInt(IntSize, flag),
5528 Context->IntTy, SourceLocation());
Fariborz Jahanianff127882009-12-23 21:52:32 +00005529 InitExprs.push_back(FlagExp);
Steve Naroff01aec112009-12-06 21:14:13 +00005530 }
Ted Kremenek668bf912009-02-09 20:51:47 +00005531 NewRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0], InitExprs.size(),
John McCallf89e55a2010-11-18 06:31:45 +00005532 FType, VK_LValue, SourceLocation());
John McCall2de56d12010-08-25 11:45:40 +00005533 NewRep = new (Context) UnaryOperator(NewRep, UO_AddrOf,
Mike Stump1eb44332009-09-09 15:08:12 +00005534 Context->getPointerType(NewRep->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00005535 VK_RValue, OK_Ordinary, SourceLocation());
John McCalla5bbc502010-11-15 09:46:46 +00005536 NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00005537 NewRep);
Steve Narofffa15fd92008-10-28 20:29:00 +00005538 BlockDeclRefs.clear();
5539 BlockByRefDecls.clear();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00005540 BlockByRefDeclsPtrSet.clear();
Steve Narofffa15fd92008-10-28 20:29:00 +00005541 BlockByCopyDecls.clear();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00005542 BlockByCopyDeclsPtrSet.clear();
Steve Narofffa15fd92008-10-28 20:29:00 +00005543 ImportedBlockDecls.clear();
5544 return NewRep;
5545}
5546
Fariborz Jahanian42f1e652011-02-24 21:29:21 +00005547bool RewriteObjC::IsDeclStmtInForeachHeader(DeclStmt *DS) {
5548 if (const ObjCForCollectionStmt * CS =
5549 dyn_cast<ObjCForCollectionStmt>(Stmts.back()))
5550 return CS->getElement() == DS;
5551 return false;
5552}
5553
Steve Narofffa15fd92008-10-28 20:29:00 +00005554//===----------------------------------------------------------------------===//
5555// Function Body / Expression rewriting
5556//===----------------------------------------------------------------------===//
5557
5558Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Mike Stump1eb44332009-09-09 15:08:12 +00005559 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofffa15fd92008-10-28 20:29:00 +00005560 isa<DoStmt>(S) || isa<ForStmt>(S))
5561 Stmts.push_back(S);
5562 else if (isa<ObjCForCollectionStmt>(S)) {
5563 Stmts.push_back(S);
Chris Lattner4824fcd2010-01-09 21:45:57 +00005564 ObjCBcLabelNo.push_back(++BcLabelCount);
Steve Narofffa15fd92008-10-28 20:29:00 +00005565 }
Mike Stump1eb44332009-09-09 15:08:12 +00005566
John McCall4b9c2d22011-11-06 09:01:30 +00005567 // Pseudo-object operations and ivar references need special
5568 // treatment because we're going to recursively rewrite them.
5569 if (PseudoObjectExpr *PseudoOp = dyn_cast<PseudoObjectExpr>(S)) {
5570 if (isa<BinaryOperator>(PseudoOp->getSyntacticForm())) {
5571 return RewritePropertyOrImplicitSetter(PseudoOp);
5572 } else {
5573 return RewritePropertyOrImplicitGetter(PseudoOp);
5574 }
5575 } else if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
5576 return RewriteObjCIvarRefExpr(IvarRefExpr);
5577 }
5578
Steve Narofffa15fd92008-10-28 20:29:00 +00005579 SourceRange OrigStmtRange = S->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00005580
Steve Narofffa15fd92008-10-28 20:29:00 +00005581 // Perform a bottom up rewrite of all children.
John McCall7502c1d2011-02-13 04:07:26 +00005582 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Narofffa15fd92008-10-28 20:29:00 +00005583 if (*CI) {
John McCall4b9c2d22011-11-06 09:01:30 +00005584 Stmt *childStmt = (*CI);
5585 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(childStmt);
Fariborz Jahanian1d015312011-04-11 21:17:02 +00005586 if (newStmt) {
John McCall4b9c2d22011-11-06 09:01:30 +00005587 *CI = newStmt;
Fariborz Jahanian1d015312011-04-11 21:17:02 +00005588 }
Nick Lewycky7e749242010-10-31 21:07:24 +00005589 }
Mike Stump1eb44332009-09-09 15:08:12 +00005590
Steve Narofffa15fd92008-10-28 20:29:00 +00005591 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00005592 SmallVector<BlockDeclRefExpr *, 8> InnerBlockDeclRefs;
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00005593 llvm::SmallPtrSet<const DeclContext *, 8> InnerContexts;
5594 InnerContexts.insert(BE->getBlockDecl());
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00005595 ImportedLocalExternalDecls.clear();
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005596 GetInnerBlockDeclRefExprs(BE->getBody(),
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00005597 InnerBlockDeclRefs, InnerContexts);
Steve Narofffa15fd92008-10-28 20:29:00 +00005598 // Rewrite the block body in place.
Fariborz Jahanianda4ad9f2010-11-08 18:37:50 +00005599 Stmt *SaveCurrentBody = CurrentBody;
5600 CurrentBody = BE->getBody();
5601 PropParentMap = 0;
Fariborz Jahanianf23a0ff2011-08-02 20:28:46 +00005602 // block literal on rhs of a property-dot-sytax assignment
5603 // must be replaced by its synthesize ast so getRewrittenText
5604 // works as expected. In this case, what actually ends up on RHS
5605 // is the blockTranscribed which is the helper function for the
5606 // block literal; as in: self.c = ^() {[ace ARR];};
5607 bool saveDisableReplaceStmt = DisableReplaceStmt;
5608 DisableReplaceStmt = false;
Steve Narofffa15fd92008-10-28 20:29:00 +00005609 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
Fariborz Jahanianf23a0ff2011-08-02 20:28:46 +00005610 DisableReplaceStmt = saveDisableReplaceStmt;
Fariborz Jahanianda4ad9f2010-11-08 18:37:50 +00005611 CurrentBody = SaveCurrentBody;
5612 PropParentMap = 0;
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00005613 ImportedLocalExternalDecls.clear();
Steve Narofffa15fd92008-10-28 20:29:00 +00005614 // Now we snarf the rewritten text and stash it away for later use.
Fariborz Jahanianf23a0ff2011-08-02 20:28:46 +00005615 std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005616 RewrittenBlockExprs[BE] = Str;
Mike Stump1eb44332009-09-09 15:08:12 +00005617
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005618 Stmt *blockTranscribed = SynthBlockInitExpr(BE, InnerBlockDeclRefs);
5619
Steve Narofffa15fd92008-10-28 20:29:00 +00005620 //blockTranscribed->dump();
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005621 ReplaceStmt(S, blockTranscribed);
Steve Narofffa15fd92008-10-28 20:29:00 +00005622 return blockTranscribed;
5623 }
5624 // Handle specific things.
5625 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
5626 return RewriteAtEncode(AtEncode);
Mike Stump1eb44332009-09-09 15:08:12 +00005627
Steve Narofffa15fd92008-10-28 20:29:00 +00005628 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
5629 return RewriteAtSelector(AtSelector);
Mike Stump1eb44332009-09-09 15:08:12 +00005630
Steve Narofffa15fd92008-10-28 20:29:00 +00005631 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
5632 return RewriteObjCStringLiteral(AtString);
Mike Stump1eb44332009-09-09 15:08:12 +00005633
Steve Narofffa15fd92008-10-28 20:29:00 +00005634 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
Steve Naroffc77a6362008-12-04 16:24:46 +00005635#if 0
Steve Narofffa15fd92008-10-28 20:29:00 +00005636 // Before we rewrite it, put the original message expression in a comment.
5637 SourceLocation startLoc = MessExpr->getLocStart();
5638 SourceLocation endLoc = MessExpr->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +00005639
Steve Narofffa15fd92008-10-28 20:29:00 +00005640 const char *startBuf = SM->getCharacterData(startLoc);
5641 const char *endBuf = SM->getCharacterData(endLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00005642
Steve Narofffa15fd92008-10-28 20:29:00 +00005643 std::string messString;
5644 messString += "// ";
5645 messString.append(startBuf, endBuf-startBuf+1);
5646 messString += "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00005647
5648 // FIXME: Missing definition of
Steve Narofffa15fd92008-10-28 20:29:00 +00005649 // InsertText(clang::SourceLocation, char const*, unsigned int).
5650 // InsertText(startLoc, messString.c_str(), messString.size());
5651 // Tried this, but it didn't work either...
5652 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroffc77a6362008-12-04 16:24:46 +00005653#endif
Steve Narofffa15fd92008-10-28 20:29:00 +00005654 return RewriteMessageExpr(MessExpr);
5655 }
Mike Stump1eb44332009-09-09 15:08:12 +00005656
Steve Narofffa15fd92008-10-28 20:29:00 +00005657 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
5658 return RewriteObjCTryStmt(StmtTry);
5659
5660 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
5661 return RewriteObjCSynchronizedStmt(StmtTry);
5662
5663 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
5664 return RewriteObjCThrowStmt(StmtThrow);
Mike Stump1eb44332009-09-09 15:08:12 +00005665
Steve Narofffa15fd92008-10-28 20:29:00 +00005666 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
5667 return RewriteObjCProtocolExpr(ProtocolExp);
Mike Stump1eb44332009-09-09 15:08:12 +00005668
5669 if (ObjCForCollectionStmt *StmtForCollection =
Steve Narofffa15fd92008-10-28 20:29:00 +00005670 dyn_cast<ObjCForCollectionStmt>(S))
Mike Stump1eb44332009-09-09 15:08:12 +00005671 return RewriteObjCForCollectionStmt(StmtForCollection,
Steve Narofffa15fd92008-10-28 20:29:00 +00005672 OrigStmtRange.getEnd());
5673 if (BreakStmt *StmtBreakStmt =
5674 dyn_cast<BreakStmt>(S))
5675 return RewriteBreakStmt(StmtBreakStmt);
5676 if (ContinueStmt *StmtContinueStmt =
5677 dyn_cast<ContinueStmt>(S))
5678 return RewriteContinueStmt(StmtContinueStmt);
Mike Stump1eb44332009-09-09 15:08:12 +00005679
5680 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
Steve Narofffa15fd92008-10-28 20:29:00 +00005681 // and cast exprs.
5682 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
5683 // FIXME: What we're doing here is modifying the type-specifier that
5684 // precedes the first Decl. In the future the DeclGroup should have
Mike Stump1eb44332009-09-09 15:08:12 +00005685 // a separate type-specifier that we can rewrite.
Steve Naroff3d7e7862009-12-05 15:55:59 +00005686 // NOTE: We need to avoid rewriting the DeclStmt if it is within
5687 // the context of an ObjCForCollectionStmt. For example:
5688 // NSArray *someArray;
5689 // for (id <FooProtocol> index in someArray) ;
5690 // This is because RewriteObjCForCollectionStmt() does textual rewriting
5691 // and it depends on the original text locations/positions.
Fariborz Jahanian42f1e652011-02-24 21:29:21 +00005692 if (Stmts.empty() || !IsDeclStmtInForeachHeader(DS))
Steve Naroff3d7e7862009-12-05 15:55:59 +00005693 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
Mike Stump1eb44332009-09-09 15:08:12 +00005694
Steve Narofffa15fd92008-10-28 20:29:00 +00005695 // Blocks rewrite rules.
5696 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
5697 DI != DE; ++DI) {
Douglas Gregor4afa39d2009-01-20 01:17:11 +00005698 Decl *SD = *DI;
Steve Narofffa15fd92008-10-28 20:29:00 +00005699 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
Steve Naroff01f2ffa2008-12-11 21:05:33 +00005700 if (isTopLevelBlockPointerType(ND->getType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00005701 RewriteBlockPointerDecl(ND);
Mike Stump1eb44332009-09-09 15:08:12 +00005702 else if (ND->getType()->isFunctionPointerType())
Steve Narofffa15fd92008-10-28 20:29:00 +00005703 CheckFunctionPointerDecl(ND->getType(), ND);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00005704 if (VarDecl *VD = dyn_cast<VarDecl>(SD)) {
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005705 if (VD->hasAttr<BlocksAttr>()) {
5706 static unsigned uniqueByrefDeclCount = 0;
5707 assert(!BlockByRefDeclNo.count(ND) &&
5708 "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
5709 BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005710 RewriteByRefVar(VD);
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005711 }
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00005712 else
5713 RewriteTypeOfDecl(VD);
5714 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005715 }
Richard Smith162e1c12011-04-15 14:24:37 +00005716 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(SD)) {
Steve Naroff01f2ffa2008-12-11 21:05:33 +00005717 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00005718 RewriteBlockPointerDecl(TD);
Mike Stump1eb44332009-09-09 15:08:12 +00005719 else if (TD->getUnderlyingType()->isFunctionPointerType())
Steve Narofffa15fd92008-10-28 20:29:00 +00005720 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5721 }
5722 }
5723 }
Mike Stump1eb44332009-09-09 15:08:12 +00005724
Steve Narofffa15fd92008-10-28 20:29:00 +00005725 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
5726 RewriteObjCQualifiedInterfaceTypes(CE);
Mike Stump1eb44332009-09-09 15:08:12 +00005727
5728 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofffa15fd92008-10-28 20:29:00 +00005729 isa<DoStmt>(S) || isa<ForStmt>(S)) {
5730 assert(!Stmts.empty() && "Statement stack is empty");
Mike Stump1eb44332009-09-09 15:08:12 +00005731 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
5732 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
Steve Narofffa15fd92008-10-28 20:29:00 +00005733 && "Statement stack mismatch");
5734 Stmts.pop_back();
5735 }
5736 // Handle blocks rewriting.
5737 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(S)) {
5738 if (BDRE->isByRef())
Steve Naroff621edce2009-04-29 16:37:50 +00005739 return RewriteBlockDeclRefExpr(BDRE);
Steve Narofffa15fd92008-10-28 20:29:00 +00005740 }
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00005741 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
5742 ValueDecl *VD = DRE->getDecl();
5743 if (VD->hasAttr<BlocksAttr>())
5744 return RewriteBlockDeclRefExpr(DRE);
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00005745 if (HasLocalVariableExternalStorage(VD))
5746 return RewriteLocalVariableExternalStorage(DRE);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00005747 }
5748
Steve Narofffa15fd92008-10-28 20:29:00 +00005749 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00005750 if (CE->getCallee()->getType()->isBlockPointerType()) {
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00005751 Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00005752 ReplaceStmt(S, BlockCall);
5753 return BlockCall;
5754 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005755 }
Steve Naroffb2f9e512008-11-03 23:29:32 +00005756 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005757 RewriteCastExpr(CE);
5758 }
5759#if 0
5760 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
Sebastian Redl906082e2010-07-20 04:20:21 +00005761 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(),
5762 ICE->getSubExpr(),
5763 SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00005764 // Get the new text.
5765 std::string SStr;
5766 llvm::raw_string_ostream Buf(SStr);
Eli Friedman3a9eb442009-05-30 05:19:26 +00005767 Replacement->printPretty(Buf, *Context);
Steve Narofffa15fd92008-10-28 20:29:00 +00005768 const std::string &Str = Buf.str();
5769
5770 printf("CAST = %s\n", &Str[0]);
5771 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
5772 delete S;
5773 return Replacement;
5774 }
5775#endif
5776 // Return this stmt unmodified.
5777 return S;
5778}
5779
Steve Naroff3d7e7862009-12-05 15:55:59 +00005780void RewriteObjC::RewriteRecordBody(RecordDecl *RD) {
5781 for (RecordDecl::field_iterator i = RD->field_begin(),
5782 e = RD->field_end(); i != e; ++i) {
5783 FieldDecl *FD = *i;
5784 if (isTopLevelBlockPointerType(FD->getType()))
5785 RewriteBlockPointerDecl(FD);
5786 if (FD->getType()->isObjCQualifiedIdType() ||
5787 FD->getType()->isObjCQualifiedInterfaceType())
5788 RewriteObjCQualifiedInterfaceTypes(FD);
5789 }
5790}
5791
Steve Narofffa15fd92008-10-28 20:29:00 +00005792/// HandleDeclInMainFile - This is called for each top-level decl defined in the
5793/// main file of the input.
5794void RewriteObjC::HandleDeclInMainFile(Decl *D) {
5795 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroffcb735302008-12-17 00:20:22 +00005796 if (FD->isOverloadedOperator())
5797 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005798
Steve Narofffa15fd92008-10-28 20:29:00 +00005799 // Since function prototypes don't have ParmDecl's, we check the function
5800 // prototype. This enables us to rewrite function declarations and
5801 // definitions using the same code.
Douglas Gregor72564e72009-02-26 23:50:07 +00005802 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
Steve Narofffa15fd92008-10-28 20:29:00 +00005803
Sebastian Redld3a413d2009-04-26 20:35:05 +00005804 // FIXME: If this should support Obj-C++, support CXXTryStmt
Argyrios Kyrtzidis5f1bfc12010-07-07 11:31:34 +00005805 if (CompoundStmt *Body = dyn_cast_or_null<CompoundStmt>(FD->getBody())) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005806 CurFunctionDef = FD;
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00005807 CurFunctionDeclToDeclareForBlock = FD;
Steve Naroff8599e7a2008-12-08 16:43:47 +00005808 CurrentBody = Body;
Ted Kremenekeaab2062009-03-12 18:33:24 +00005809 Body =
5810 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5811 FD->setBody(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00005812 CurrentBody = 0;
5813 if (PropParentMap) {
5814 delete PropParentMap;
5815 PropParentMap = 0;
5816 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005817 // This synthesizes and inserts the block "impl" struct, invoke function,
5818 // and any copy/dispose helper functions.
5819 InsertBlockLiteralsWithinFunction(FD);
5820 CurFunctionDef = 0;
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00005821 CurFunctionDeclToDeclareForBlock = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00005822 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005823 return;
5824 }
5825 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00005826 if (CompoundStmt *Body = MD->getCompoundBody()) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005827 CurMethodDef = MD;
Steve Naroff8599e7a2008-12-08 16:43:47 +00005828 CurrentBody = Body;
Ted Kremenekeaab2062009-03-12 18:33:24 +00005829 Body =
5830 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5831 MD->setBody(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00005832 CurrentBody = 0;
5833 if (PropParentMap) {
5834 delete PropParentMap;
5835 PropParentMap = 0;
5836 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005837 InsertBlockLiteralsWithinMethod(MD);
5838 CurMethodDef = 0;
5839 }
5840 }
5841 if (ObjCImplementationDecl *CI = dyn_cast<ObjCImplementationDecl>(D))
5842 ClassImplementation.push_back(CI);
5843 else if (ObjCCategoryImplDecl *CI = dyn_cast<ObjCCategoryImplDecl>(D))
5844 CategoryImplementation.push_back(CI);
Fariborz Jahanian95ed7782011-08-27 20:50:59 +00005845 else if (isa<ObjCClassDecl>(D))
David Blaikieb219cfc2011-09-23 05:06:16 +00005846 llvm_unreachable("RewriteObjC::HandleDeclInMainFile - ObjCClassDecl");
Steve Narofffa15fd92008-10-28 20:29:00 +00005847 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
5848 RewriteObjCQualifiedInterfaceTypes(VD);
Steve Naroff01f2ffa2008-12-11 21:05:33 +00005849 if (isTopLevelBlockPointerType(VD->getType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00005850 RewriteBlockPointerDecl(VD);
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005851 else if (VD->getType()->isFunctionPointerType()) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005852 CheckFunctionPointerDecl(VD->getType(), VD);
5853 if (VD->getInit()) {
Steve Naroffb2f9e512008-11-03 23:29:32 +00005854 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005855 RewriteCastExpr(CE);
5856 }
5857 }
Steve Naroff3d7e7862009-12-05 15:55:59 +00005858 } else if (VD->getType()->isRecordType()) {
5859 RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
John McCall5e1cdac2011-10-07 06:10:15 +00005860 if (RD->isCompleteDefinition())
Steve Naroff3d7e7862009-12-05 15:55:59 +00005861 RewriteRecordBody(RD);
Steve Narofffa15fd92008-10-28 20:29:00 +00005862 }
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005863 if (VD->getInit()) {
5864 GlobalVarDecl = VD;
Steve Naroff8599e7a2008-12-08 16:43:47 +00005865 CurrentBody = VD->getInit();
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005866 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
Steve Naroff8599e7a2008-12-08 16:43:47 +00005867 CurrentBody = 0;
5868 if (PropParentMap) {
5869 delete PropParentMap;
5870 PropParentMap = 0;
5871 }
Mike Stump1eb44332009-09-09 15:08:12 +00005872 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(),
Daniel Dunbar4087f272010-08-17 22:39:59 +00005873 VD->getName());
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005874 GlobalVarDecl = 0;
5875
5876 // This is needed for blocks.
Steve Naroffb2f9e512008-11-03 23:29:32 +00005877 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005878 RewriteCastExpr(CE);
5879 }
5880 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005881 return;
5882 }
Richard Smith162e1c12011-04-15 14:24:37 +00005883 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
Steve Naroff01f2ffa2008-12-11 21:05:33 +00005884 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00005885 RewriteBlockPointerDecl(TD);
Mike Stump1eb44332009-09-09 15:08:12 +00005886 else if (TD->getUnderlyingType()->isFunctionPointerType())
Steve Narofffa15fd92008-10-28 20:29:00 +00005887 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5888 return;
5889 }
5890 if (RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
John McCall5e1cdac2011-10-07 06:10:15 +00005891 if (RD->isCompleteDefinition())
Steve Naroff3d7e7862009-12-05 15:55:59 +00005892 RewriteRecordBody(RD);
Steve Narofffa15fd92008-10-28 20:29:00 +00005893 return;
5894 }
5895 // Nothing yet.
5896}
5897
Chris Lattnerdacbc5d2009-03-28 04:11:33 +00005898void RewriteObjC::HandleTranslationUnit(ASTContext &C) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005899 if (Diags.hasErrorOccurred())
5900 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005901
Steve Narofffa15fd92008-10-28 20:29:00 +00005902 RewriteInclude();
Mike Stump1eb44332009-09-09 15:08:12 +00005903
Steve Naroff621edce2009-04-29 16:37:50 +00005904 // Here's a great place to add any extra declarations that may be needed.
5905 // Write out meta data for each @protocol(<expr>).
Mike Stump1eb44332009-09-09 15:08:12 +00005906 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Steve Naroff621edce2009-04-29 16:37:50 +00005907 E = ProtocolExprDecls.end(); I != E; ++I)
5908 RewriteObjCProtocolMetaData(*I, "", "", Preamble);
5909
Benjamin Kramerd999b372010-02-14 14:14:16 +00005910 InsertText(SM->getLocForStartOfFile(MainFileID), Preamble, false);
Steve Naroff0aab7962008-11-14 14:10:01 +00005911 if (ClassImplementation.size() || CategoryImplementation.size())
5912 RewriteImplementations();
Steve Naroff621edce2009-04-29 16:37:50 +00005913
Steve Narofffa15fd92008-10-28 20:29:00 +00005914 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
5915 // we are done.
Mike Stump1eb44332009-09-09 15:08:12 +00005916 if (const RewriteBuffer *RewriteBuf =
Steve Narofffa15fd92008-10-28 20:29:00 +00005917 Rewrite.getRewriteBufferFor(MainFileID)) {
5918 //printf("Changed:\n");
5919 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
5920 } else {
Benjamin Kramerd999b372010-02-14 14:14:16 +00005921 llvm::errs() << "No changes\n";
Steve Narofffa15fd92008-10-28 20:29:00 +00005922 }
Steve Narofface66252008-11-13 20:07:04 +00005923
Steve Naroff621edce2009-04-29 16:37:50 +00005924 if (ClassImplementation.size() || CategoryImplementation.size() ||
5925 ProtocolExprDecls.size()) {
Steve Naroff0aab7962008-11-14 14:10:01 +00005926 // Rewrite Objective-c meta data*
5927 std::string ResultStr;
Fariborz Jahanian58457172011-12-05 18:43:13 +00005928 RewriteMetaDataIntoBuffer(ResultStr);
Steve Naroff0aab7962008-11-14 14:10:01 +00005929 // Emit metadata.
5930 *OutFile << ResultStr;
5931 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005932 OutFile->flush();
5933}