blob: ba5d669f0835900e8fa98ad2fce06befcae5c5e4 [file] [log] [blame]
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001//===--- RewriteObjC.cpp - Playground for the code rewriter ---------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// Hacks and fun related to the code rewriter.
11//
12//===----------------------------------------------------------------------===//
13
Ted Kremenek305c6132012-09-01 05:09:24 +000014#include "clang/Rewrite/Frontend/ASTConsumers.h"
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +000015#include "clang/AST/AST.h"
16#include "clang/AST/ASTConsumer.h"
Benjamin Kramer2fa67ef2012-12-01 15:09:41 +000017#include "clang/AST/Attr.h"
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +000018#include "clang/AST/ParentMap.h"
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +000019#include "clang/Basic/Diagnostic.h"
Benjamin Kramer2fa67ef2012-12-01 15:09:41 +000020#include "clang/Basic/IdentifierTable.h"
21#include "clang/Basic/SourceManager.h"
Benjamin Kramer9852f582012-12-01 16:35:25 +000022#include "clang/Basic/TargetInfo.h"
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +000023#include "clang/Lex/Lexer.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000024#include "clang/Rewrite/Core/Rewriter.h"
Benjamin Kramer2fa67ef2012-12-01 15:09:41 +000025#include "llvm/ADT/DenseSet.h"
26#include "llvm/ADT/OwningPtr.h"
27#include "llvm/ADT/SmallPtrSet.h"
28#include "llvm/ADT/StringExtras.h"
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +000029#include "llvm/Support/MemoryBuffer.h"
30#include "llvm/Support/raw_ostream.h"
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +000031
32using namespace clang;
33using llvm::utostr;
34
35namespace {
36 class RewriteModernObjC : public ASTConsumer {
37 protected:
38
39 enum {
40 BLOCK_FIELD_IS_OBJECT = 3, /* id, NSObject, __attribute__((NSObject)),
41 block, ... */
42 BLOCK_FIELD_IS_BLOCK = 7, /* a block variable */
43 BLOCK_FIELD_IS_BYREF = 8, /* the on stack structure holding the
44 __block variable */
45 BLOCK_FIELD_IS_WEAK = 16, /* declared __weak, only used in byref copy
46 helpers */
47 BLOCK_BYREF_CALLER = 128, /* called from __block (byref) copy/dispose
48 support routines */
49 BLOCK_BYREF_CURRENT_MAX = 256
50 };
51
52 enum {
53 BLOCK_NEEDS_FREE = (1 << 24),
54 BLOCK_HAS_COPY_DISPOSE = (1 << 25),
55 BLOCK_HAS_CXX_OBJ = (1 << 26),
56 BLOCK_IS_GC = (1 << 27),
57 BLOCK_IS_GLOBAL = (1 << 28),
58 BLOCK_HAS_DESCRIPTOR = (1 << 29)
59 };
60 static const int OBJC_ABI_VERSION = 7;
61
62 Rewriter Rewrite;
63 DiagnosticsEngine &Diags;
64 const LangOptions &LangOpts;
65 ASTContext *Context;
66 SourceManager *SM;
67 TranslationUnitDecl *TUDecl;
68 FileID MainFileID;
69 const char *MainFileStart, *MainFileEnd;
70 Stmt *CurrentBody;
71 ParentMap *PropParentMap; // created lazily.
72 std::string InFileName;
73 raw_ostream* OutFile;
74 std::string Preamble;
75
76 TypeDecl *ProtocolTypeDecl;
77 VarDecl *GlobalVarDecl;
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +000078 Expr *GlobalConstructionExp;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +000079 unsigned RewriteFailedDiag;
Fariborz Jahaniand13c2c22012-03-22 19:54:39 +000080 unsigned GlobalBlockRewriteFailedDiag;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +000081 // ObjC string constant support.
82 unsigned NumObjCStringLiterals;
83 VarDecl *ConstantStringClassReference;
84 RecordDecl *NSStringRecord;
85
86 // ObjC foreach break/continue generation support.
87 int BcLabelCount;
88
89 unsigned TryFinallyContainsReturnDiag;
90 // Needed for super.
91 ObjCMethodDecl *CurMethodDef;
92 RecordDecl *SuperStructDecl;
93 RecordDecl *ConstantStringDecl;
94
95 FunctionDecl *MsgSendFunctionDecl;
96 FunctionDecl *MsgSendSuperFunctionDecl;
97 FunctionDecl *MsgSendStretFunctionDecl;
98 FunctionDecl *MsgSendSuperStretFunctionDecl;
99 FunctionDecl *MsgSendFpretFunctionDecl;
100 FunctionDecl *GetClassFunctionDecl;
101 FunctionDecl *GetMetaClassFunctionDecl;
102 FunctionDecl *GetSuperClassFunctionDecl;
103 FunctionDecl *SelGetUidFunctionDecl;
104 FunctionDecl *CFStringFunctionDecl;
105 FunctionDecl *SuperContructorFunctionDecl;
106 FunctionDecl *CurFunctionDef;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000107
108 /* Misc. containers needed for meta-data rewrite. */
109 SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
110 SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
111 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs;
112 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> ObjCSynthesizedProtocols;
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +0000113 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCWrittenInterfaces;
Fariborz Jahanian8fba8942012-04-30 23:20:30 +0000114 llvm::SmallPtrSet<TagDecl*, 32> GlobalDefinedTags;
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +0000115 SmallVector<ObjCInterfaceDecl*, 32> ObjCInterfacesSeen;
Fariborz Jahanian88f7f752012-03-14 23:18:19 +0000116 /// DefinedNonLazyClasses - List of defined "non-lazy" classes.
117 SmallVector<ObjCInterfaceDecl*, 8> DefinedNonLazyClasses;
118
119 /// DefinedNonLazyCategories - List of defined "non-lazy" categories.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000120 SmallVector<ObjCCategoryDecl *, 8> DefinedNonLazyCategories;
Fariborz Jahanian88f7f752012-03-14 23:18:19 +0000121
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000122 SmallVector<Stmt *, 32> Stmts;
123 SmallVector<int, 8> ObjCBcLabelNo;
124 // Remember all the @protocol(<expr>) expressions.
125 llvm::SmallPtrSet<ObjCProtocolDecl *, 32> ProtocolExprDecls;
126
127 llvm::DenseSet<uint64_t> CopyDestroyCache;
128
129 // Block expressions.
130 SmallVector<BlockExpr *, 32> Blocks;
131 SmallVector<int, 32> InnerDeclRefsCount;
John McCallf4b88a42012-03-10 09:33:50 +0000132 SmallVector<DeclRefExpr *, 32> InnerDeclRefs;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000133
John McCallf4b88a42012-03-10 09:33:50 +0000134 SmallVector<DeclRefExpr *, 32> BlockDeclRefs;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000135
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +0000136
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000137 // Block related declarations.
138 SmallVector<ValueDecl *, 8> BlockByCopyDecls;
139 llvm::SmallPtrSet<ValueDecl *, 8> BlockByCopyDeclsPtrSet;
140 SmallVector<ValueDecl *, 8> BlockByRefDecls;
141 llvm::SmallPtrSet<ValueDecl *, 8> BlockByRefDeclsPtrSet;
142 llvm::DenseMap<ValueDecl *, unsigned> BlockByRefDeclNo;
143 llvm::SmallPtrSet<ValueDecl *, 8> ImportedBlockDecls;
144 llvm::SmallPtrSet<VarDecl *, 8> ImportedLocalExternalDecls;
145
146 llvm::DenseMap<BlockExpr *, std::string> RewrittenBlockExprs;
Fariborz Jahanian72c88f12012-02-22 18:13:25 +0000147 llvm::DenseMap<ObjCInterfaceDecl *,
148 llvm::SmallPtrSet<ObjCIvarDecl *, 8> > ReferencedIvars;
149
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +0000150 // ivar bitfield grouping containers
151 llvm::DenseSet<const ObjCInterfaceDecl *> ObjCInterefaceHasBitfieldGroups;
152 llvm::DenseMap<const ObjCIvarDecl* , unsigned> IvarGroupNumber;
153 // This container maps an <class, group number for ivar> tuple to the type
154 // of the struct where the bitfield belongs.
155 llvm::DenseMap<std::pair<const ObjCInterfaceDecl*, unsigned>, QualType> GroupRecordType;
Fariborz Jahanian31c4a4b2013-02-07 22:50:40 +0000156 SmallVector<FunctionDecl*, 32> FunctionDefinitionsSeen;
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +0000157
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000158 // This maps an original source AST to it's rewritten form. This allows
159 // us to avoid rewriting the same node twice (which is very uncommon).
160 // This is needed to support some of the exotic property rewriting.
161 llvm::DenseMap<Stmt *, Stmt *> ReplacedNodes;
162
163 // Needed for header files being rewritten
164 bool IsHeader;
165 bool SilenceRewriteMacroWarning;
Fariborz Jahanianada71912013-02-08 00:27:34 +0000166 bool GenerateLineInfo;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000167 bool objc_impl_method;
168
169 bool DisableReplaceStmt;
170 class DisableReplaceStmtScope {
171 RewriteModernObjC &R;
172 bool SavedValue;
173
174 public:
175 DisableReplaceStmtScope(RewriteModernObjC &R)
176 : R(R), SavedValue(R.DisableReplaceStmt) {
177 R.DisableReplaceStmt = true;
178 }
179 ~DisableReplaceStmtScope() {
180 R.DisableReplaceStmt = SavedValue;
181 }
182 };
183 void InitializeCommon(ASTContext &context);
184
185 public:
Fariborz Jahanian90af4e22012-02-14 17:19:02 +0000186 llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000187 // Top Level Driver code.
188 virtual bool HandleTopLevelDecl(DeclGroupRef D) {
189 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
190 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(*I)) {
191 if (!Class->isThisDeclarationADefinition()) {
192 RewriteForwardClassDecl(D);
193 break;
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +0000194 } else {
195 // Keep track of all interface declarations seen.
Fariborz Jahanianf3295272012-02-24 21:42:38 +0000196 ObjCInterfacesSeen.push_back(Class);
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +0000197 break;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000198 }
199 }
200
201 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>(*I)) {
202 if (!Proto->isThisDeclarationADefinition()) {
203 RewriteForwardProtocolDecl(D);
204 break;
205 }
206 }
207
Fariborz Jahanian31c4a4b2013-02-07 22:50:40 +0000208 if (FunctionDecl *FDecl = dyn_cast<FunctionDecl>(*I)) {
209 // Under modern abi, we cannot translate body of the function
210 // yet until all class extensions and its implementation is seen.
211 // This is because they may introduce new bitfields which must go
212 // into their grouping struct.
213 if (FDecl->isThisDeclarationADefinition() &&
214 // Not c functions defined inside an objc container.
215 !FDecl->isTopLevelDeclInObjCContainer()) {
216 FunctionDefinitionsSeen.push_back(FDecl);
217 break;
218 }
219 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000220 HandleTopLevelSingleDecl(*I);
221 }
222 return true;
223 }
224 void HandleTopLevelSingleDecl(Decl *D);
225 void HandleDeclInMainFile(Decl *D);
226 RewriteModernObjC(std::string inFile, raw_ostream *OS,
227 DiagnosticsEngine &D, const LangOptions &LOpts,
Fariborz Jahanianada71912013-02-08 00:27:34 +0000228 bool silenceMacroWarn, bool LineInfo);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000229
230 ~RewriteModernObjC() {}
231
232 virtual void HandleTranslationUnit(ASTContext &C);
233
234 void ReplaceStmt(Stmt *Old, Stmt *New) {
235 Stmt *ReplacingStmt = ReplacedNodes[Old];
236
237 if (ReplacingStmt)
238 return; // We can't rewrite the same node twice.
239
240 if (DisableReplaceStmt)
241 return;
242
243 // If replacement succeeded or warning disabled return with no warning.
244 if (!Rewrite.ReplaceStmt(Old, New)) {
245 ReplacedNodes[Old] = New;
246 return;
247 }
248 if (SilenceRewriteMacroWarning)
249 return;
250 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
251 << Old->getSourceRange();
252 }
253
254 void ReplaceStmtWithRange(Stmt *Old, Stmt *New, SourceRange SrcRange) {
255 if (DisableReplaceStmt)
256 return;
257
258 // Measure the old text.
259 int Size = Rewrite.getRangeSize(SrcRange);
260 if (Size == -1) {
261 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
262 << Old->getSourceRange();
263 return;
264 }
265 // Get the new text.
266 std::string SStr;
267 llvm::raw_string_ostream S(SStr);
Richard Smithd1420c62012-08-16 03:56:14 +0000268 New->printPretty(S, 0, PrintingPolicy(LangOpts));
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000269 const std::string &Str = S.str();
270
271 // If replacement succeeded or warning disabled return with no warning.
272 if (!Rewrite.ReplaceText(SrcRange.getBegin(), Size, Str)) {
273 ReplacedNodes[Old] = New;
274 return;
275 }
276 if (SilenceRewriteMacroWarning)
277 return;
278 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
279 << Old->getSourceRange();
280 }
281
282 void InsertText(SourceLocation Loc, StringRef Str,
283 bool InsertAfter = true) {
284 // If insertion succeeded or warning disabled return with no warning.
285 if (!Rewrite.InsertText(Loc, Str, InsertAfter) ||
286 SilenceRewriteMacroWarning)
287 return;
288
289 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
290 }
291
292 void ReplaceText(SourceLocation Start, unsigned OrigLength,
293 StringRef Str) {
294 // If removal succeeded or warning disabled return with no warning.
295 if (!Rewrite.ReplaceText(Start, OrigLength, Str) ||
296 SilenceRewriteMacroWarning)
297 return;
298
299 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
300 }
301
302 // Syntactic Rewriting.
303 void RewriteRecordBody(RecordDecl *RD);
304 void RewriteInclude();
Fariborz Jahanian96205962012-11-06 17:30:23 +0000305 void RewriteLineDirective(const Decl *D);
Fariborz Jahanianf616ae22012-11-06 23:25:49 +0000306 void ConvertSourceLocationToLineDirective(SourceLocation Loc,
307 std::string &LineString);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000308 void RewriteForwardClassDecl(DeclGroupRef D);
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000309 void RewriteForwardClassDecl(const SmallVector<Decl *, 8> &DG);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000310 void RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
311 const std::string &typedefString);
312 void RewriteImplementations();
313 void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
314 ObjCImplementationDecl *IMD,
315 ObjCCategoryImplDecl *CID);
316 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
317 void RewriteImplementationDecl(Decl *Dcl);
318 void RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
319 ObjCMethodDecl *MDecl, std::string &ResultStr);
320 void RewriteTypeIntoString(QualType T, std::string &ResultStr,
321 const FunctionType *&FPRetType);
322 void RewriteByRefString(std::string &ResultStr, const std::string &Name,
323 ValueDecl *VD, bool def=false);
324 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
325 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
326 void RewriteForwardProtocolDecl(DeclGroupRef D);
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000327 void RewriteForwardProtocolDecl(const SmallVector<Decl *, 8> &DG);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000328 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
329 void RewriteProperty(ObjCPropertyDecl *prop);
330 void RewriteFunctionDecl(FunctionDecl *FD);
331 void RewriteBlockPointerType(std::string& Str, QualType Type);
332 void RewriteBlockPointerTypeVariable(std::string& Str, ValueDecl *VD);
Fariborz Jahanianb75f8de2012-04-19 00:50:01 +0000333 void RewriteBlockLiteralFunctionDecl(FunctionDecl *FD);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000334 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
335 void RewriteTypeOfDecl(VarDecl *VD);
336 void RewriteObjCQualifiedInterfaceTypes(Expr *E);
Fariborz Jahanian163d3ce2012-05-08 23:54:35 +0000337
338 std::string getIvarAccessString(ObjCIvarDecl *D);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000339
340 // Expression Rewriting.
341 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
342 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
343 Stmt *RewritePropertyOrImplicitGetter(PseudoObjectExpr *Pseudo);
344 Stmt *RewritePropertyOrImplicitSetter(PseudoObjectExpr *Pseudo);
345 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
346 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
347 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian55947042012-03-27 20:17:30 +0000348 Stmt *RewriteObjCBoolLiteralExpr(ObjCBoolLiteralExpr *Exp);
Patrick Beardeb382ec2012-04-19 00:25:12 +0000349 Stmt *RewriteObjCBoxedExpr(ObjCBoxedExpr *Exp);
Fariborz Jahanian86cff602012-03-30 23:35:47 +0000350 Stmt *RewriteObjCArrayLiteralExpr(ObjCArrayLiteral *Exp);
Fariborz Jahaniane35abe12012-04-06 22:29:36 +0000351 Stmt *RewriteObjCDictionaryLiteralExpr(ObjCDictionaryLiteral *Exp);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000352 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000353 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
Fariborz Jahanian042b91d2012-05-23 23:47:20 +0000354 Stmt *RewriteObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000355 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
356 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
357 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
358 SourceLocation OrigEnd);
359 Stmt *RewriteBreakStmt(BreakStmt *S);
360 Stmt *RewriteContinueStmt(ContinueStmt *S);
361 void RewriteCastExpr(CStyleCastExpr *CE);
Fariborz Jahanianf1ee6872012-04-10 00:08:18 +0000362 void RewriteImplicitCastObjCExpr(CastExpr *IE);
Fariborz Jahanianb3f904f2012-04-03 17:35:38 +0000363 void RewriteLinkageSpec(LinkageSpecDecl *LSD);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000364
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +0000365 // Computes ivar bitfield group no.
366 unsigned ObjCIvarBitfieldGroupNo(ObjCIvarDecl *IV);
367 // Names field decl. for ivar bitfield group.
368 void ObjCIvarBitfieldGroupDecl(ObjCIvarDecl *IV, std::string &Result);
369 // Names struct type for ivar bitfield group.
370 void ObjCIvarBitfieldGroupType(ObjCIvarDecl *IV, std::string &Result);
371 // Names symbol for ivar bitfield group field offset.
372 void ObjCIvarBitfieldGroupOffset(ObjCIvarDecl *IV, std::string &Result);
373 // Given an ivar bitfield, it builds (or finds) its group record type.
374 QualType GetGroupRecordTypeForObjCIvarBitfield(ObjCIvarDecl *IV);
375 QualType SynthesizeBitfieldGroupStructType(
376 ObjCIvarDecl *IV,
377 SmallVectorImpl<ObjCIvarDecl *> &IVars);
378
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000379 // Block rewriting.
380 void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D);
381
382 // Block specific rewrite rules.
383 void RewriteBlockPointerDecl(NamedDecl *VD);
Fariborz Jahanian4fe261c2012-04-24 19:38:45 +0000384 void RewriteByRefVar(VarDecl *VD, bool firstDecl, bool lastDecl);
John McCallf4b88a42012-03-10 09:33:50 +0000385 Stmt *RewriteBlockDeclRefExpr(DeclRefExpr *VD);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000386 Stmt *RewriteLocalVariableExternalStorage(DeclRefExpr *DRE);
387 void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
388
389 void RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
390 std::string &Result);
391
Fariborz Jahanian15f87772012-02-28 22:45:07 +0000392 void RewriteObjCFieldDecl(FieldDecl *fieldDecl, std::string &Result);
Fariborz Jahanianb68258f2012-05-01 17:46:45 +0000393 bool IsTagDefinedInsideClass(ObjCContainerDecl *IDecl, TagDecl *Tag,
Fariborz Jahanian8fba8942012-04-30 23:20:30 +0000394 bool &IsNamedDefinition);
395 void RewriteLocallyDefinedNamedAggregates(FieldDecl *fieldDecl,
396 std::string &Result);
Fariborz Jahanian15f87772012-02-28 22:45:07 +0000397
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +0000398 bool RewriteObjCFieldDeclType(QualType &Type, std::string &Result);
399
Fariborz Jahanian72c88f12012-02-22 18:13:25 +0000400 void RewriteIvarOffsetSymbols(ObjCInterfaceDecl *CDecl,
401 std::string &Result);
402
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000403 virtual void Initialize(ASTContext &context);
404
Benjamin Kramer48d798c2012-06-02 10:20:41 +0000405 // Misc. AST transformation routines. Sometimes they end up calling
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000406 // rewriting routines on the new ASTs.
407 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
408 Expr **args, unsigned nargs,
409 SourceLocation StartLoc=SourceLocation(),
410 SourceLocation EndLoc=SourceLocation());
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +0000411
412 Expr *SynthMsgSendStretCallExpr(FunctionDecl *MsgSendStretFlavor,
413 QualType msgSendType,
414 QualType returnType,
415 SmallVectorImpl<QualType> &ArgTypes,
416 SmallVectorImpl<Expr*> &MsgExprs,
417 ObjCMethodDecl *Method);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000418
419 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp,
420 SourceLocation StartLoc=SourceLocation(),
421 SourceLocation EndLoc=SourceLocation());
422
423 void SynthCountByEnumWithState(std::string &buf);
424 void SynthMsgSendFunctionDecl();
425 void SynthMsgSendSuperFunctionDecl();
426 void SynthMsgSendStretFunctionDecl();
427 void SynthMsgSendFpretFunctionDecl();
428 void SynthMsgSendSuperStretFunctionDecl();
429 void SynthGetClassFunctionDecl();
430 void SynthGetMetaClassFunctionDecl();
431 void SynthGetSuperClassFunctionDecl();
432 void SynthSelGetUidFunctionDecl();
433 void SynthSuperContructorFunctionDecl();
434
435 // Rewriting metadata
436 template<typename MethodIterator>
437 void RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
438 MethodIterator MethodEnd,
439 bool IsInstanceMethod,
440 StringRef prefix,
441 StringRef ClassName,
442 std::string &Result);
Fariborz Jahanianda9624a2012-02-08 19:53:58 +0000443 void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
444 std::string &Result);
Fariborz Jahanianb4ee8802012-04-30 16:57:52 +0000445 void RewriteObjCProtocolListMetaData(
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000446 const ObjCList<ObjCProtocolDecl> &Prots,
447 StringRef prefix, StringRef ClassName, std::string &Result);
Fariborz Jahanianb4ee8802012-04-30 16:57:52 +0000448 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000449 std::string &Result);
Fariborz Jahanianb4ee8802012-04-30 16:57:52 +0000450 void RewriteClassSetupInitHook(std::string &Result);
Fariborz Jahaniane0335782012-03-27 18:41:05 +0000451
Fariborz Jahanianb4ee8802012-04-30 16:57:52 +0000452 void RewriteMetaDataIntoBuffer(std::string &Result);
453 void WriteImageInfo(std::string &Result);
454 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000455 std::string &Result);
Fariborz Jahanianb4ee8802012-04-30 16:57:52 +0000456 void RewriteCategorySetupInitHook(std::string &Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000457
458 // Rewriting ivar
Fariborz Jahanianb4ee8802012-04-30 16:57:52 +0000459 void RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000460 std::string &Result);
Fariborz Jahanianb4ee8802012-04-30 16:57:52 +0000461 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000462
463
464 std::string SynthesizeByrefCopyDestroyHelper(VarDecl *VD, int flag);
465 std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
466 StringRef funcName, std::string Tag);
467 std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
468 StringRef funcName, std::string Tag);
469 std::string SynthesizeBlockImpl(BlockExpr *CE,
470 std::string Tag, std::string Desc);
471 std::string SynthesizeBlockDescriptor(std::string DescTag,
472 std::string ImplTag,
473 int i, StringRef funcName,
474 unsigned hasCopy);
475 Stmt *SynthesizeBlockCall(CallExpr *Exp, const Expr* BlockExp);
476 void SynthesizeBlockLiterals(SourceLocation FunLocStart,
477 StringRef FunName);
478 FunctionDecl *SynthBlockInitFunctionDecl(StringRef name);
479 Stmt *SynthBlockInitExpr(BlockExpr *Exp,
John McCallf4b88a42012-03-10 09:33:50 +0000480 const SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000481
482 // Misc. helper routines.
483 QualType getProtocolType();
484 void WarnAboutReturnGotoStmts(Stmt *S);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000485 void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
486 void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
487 void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
488
489 bool IsDeclStmtInForeachHeader(DeclStmt *DS);
490 void CollectBlockDeclRefInfo(BlockExpr *Exp);
491 void GetBlockDeclRefExprs(Stmt *S);
492 void GetInnerBlockDeclRefExprs(Stmt *S,
John McCallf4b88a42012-03-10 09:33:50 +0000493 SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000494 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts);
495
496 // We avoid calling Type::isBlockPointerType(), since it operates on the
497 // canonical type. We only care if the top-level type is a closure pointer.
498 bool isTopLevelBlockPointerType(QualType T) {
499 return isa<BlockPointerType>(T);
500 }
501
502 /// convertBlockPointerToFunctionPointer - Converts a block-pointer type
503 /// to a function pointer type and upon success, returns true; false
504 /// otherwise.
505 bool convertBlockPointerToFunctionPointer(QualType &T) {
506 if (isTopLevelBlockPointerType(T)) {
507 const BlockPointerType *BPT = T->getAs<BlockPointerType>();
508 T = Context->getPointerType(BPT->getPointeeType());
509 return true;
510 }
511 return false;
512 }
513
Fariborz Jahanian164d6f82012-02-13 18:57:49 +0000514 bool convertObjCTypeToCStyleType(QualType &T);
515
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000516 bool needToScanForQualifiers(QualType T);
517 QualType getSuperStructType();
518 QualType getConstantStringStructType();
519 QualType convertFunctionTypeOfBlocks(const FunctionType *FT);
520 bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
521
522 void convertToUnqualifiedObjCType(QualType &T) {
Fariborz Jahaniane35abe12012-04-06 22:29:36 +0000523 if (T->isObjCQualifiedIdType()) {
524 bool isConst = T.isConstQualified();
525 T = isConst ? Context->getObjCIdType().withConst()
526 : Context->getObjCIdType();
527 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000528 else if (T->isObjCQualifiedClassType())
529 T = Context->getObjCClassType();
530 else if (T->isObjCObjectPointerType() &&
531 T->getPointeeType()->isObjCQualifiedInterfaceType()) {
532 if (const ObjCObjectPointerType * OBJPT =
533 T->getAsObjCInterfacePointerType()) {
534 const ObjCInterfaceType *IFaceT = OBJPT->getInterfaceType();
535 T = QualType(IFaceT, 0);
536 T = Context->getPointerType(T);
537 }
538 }
539 }
540
541 // FIXME: This predicate seems like it would be useful to add to ASTContext.
542 bool isObjCType(QualType T) {
543 if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
544 return false;
545
546 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
547
548 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
549 OCT == Context->getCanonicalType(Context->getObjCClassType()))
550 return true;
551
552 if (const PointerType *PT = OCT->getAs<PointerType>()) {
553 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
554 PT->getPointeeType()->isObjCQualifiedIdType())
555 return true;
556 }
557 return false;
558 }
559 bool PointerTypeTakesAnyBlockArguments(QualType QT);
560 bool PointerTypeTakesAnyObjCQualifiedType(QualType QT);
561 void GetExtentOfArgList(const char *Name, const char *&LParen,
562 const char *&RParen);
563
564 void QuoteDoublequotes(std::string &From, std::string &To) {
565 for (unsigned i = 0; i < From.length(); i++) {
566 if (From[i] == '"')
567 To += "\\\"";
568 else
569 To += From[i];
570 }
571 }
572
573 QualType getSimpleFunctionType(QualType result,
574 const QualType *args,
575 unsigned numArgs,
576 bool variadic = false) {
577 if (result == Context->getObjCInstanceType())
578 result = Context->getObjCIdType();
579 FunctionProtoType::ExtProtoInfo fpi;
580 fpi.Variadic = variadic;
581 return Context->getFunctionType(result, args, numArgs, fpi);
582 }
583
584 // Helper function: create a CStyleCastExpr with trivial type source info.
585 CStyleCastExpr* NoTypeInfoCStyleCastExpr(ASTContext *Ctx, QualType Ty,
586 CastKind Kind, Expr *E) {
587 TypeSourceInfo *TInfo = Ctx->getTrivialTypeSourceInfo(Ty, SourceLocation());
588 return CStyleCastExpr::Create(*Ctx, Ty, VK_RValue, Kind, E, 0, TInfo,
589 SourceLocation(), SourceLocation());
590 }
Fariborz Jahanian88f7f752012-03-14 23:18:19 +0000591
592 bool ImplementationIsNonLazy(const ObjCImplDecl *OD) const {
593 IdentifierInfo* II = &Context->Idents.get("load");
594 Selector LoadSel = Context->Selectors.getSelector(0, &II);
595 return OD->getClassMethod(LoadSel) != 0;
596 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000597 };
598
599}
600
601void RewriteModernObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
602 NamedDecl *D) {
603 if (const FunctionProtoType *fproto
604 = dyn_cast<FunctionProtoType>(funcType.IgnoreParens())) {
605 for (FunctionProtoType::arg_type_iterator I = fproto->arg_type_begin(),
606 E = fproto->arg_type_end(); I && (I != E); ++I)
607 if (isTopLevelBlockPointerType(*I)) {
608 // All the args are checked/rewritten. Don't call twice!
609 RewriteBlockPointerDecl(D);
610 break;
611 }
612 }
613}
614
615void RewriteModernObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
616 const PointerType *PT = funcType->getAs<PointerType>();
617 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
618 RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
619}
620
621static bool IsHeaderFile(const std::string &Filename) {
622 std::string::size_type DotPos = Filename.rfind('.');
623
624 if (DotPos == std::string::npos) {
625 // no file extension
626 return false;
627 }
628
629 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
630 // C header: .h
631 // C++ header: .hh or .H;
632 return Ext == "h" || Ext == "hh" || Ext == "H";
633}
634
635RewriteModernObjC::RewriteModernObjC(std::string inFile, raw_ostream* OS,
636 DiagnosticsEngine &D, const LangOptions &LOpts,
Fariborz Jahanianada71912013-02-08 00:27:34 +0000637 bool silenceMacroWarn,
638 bool LineInfo)
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000639 : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(OS),
Fariborz Jahanianada71912013-02-08 00:27:34 +0000640 SilenceRewriteMacroWarning(silenceMacroWarn), GenerateLineInfo(LineInfo) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000641 IsHeader = IsHeaderFile(inFile);
642 RewriteFailedDiag = Diags.getCustomDiagID(DiagnosticsEngine::Warning,
643 "rewriting sub-expression within a macro (may not be correct)");
Fariborz Jahaniand13c2c22012-03-22 19:54:39 +0000644 // FIXME. This should be an error. But if block is not called, it is OK. And it
645 // may break including some headers.
646 GlobalBlockRewriteFailedDiag = Diags.getCustomDiagID(DiagnosticsEngine::Warning,
647 "rewriting block literal declared in global scope is not implemented");
648
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000649 TryFinallyContainsReturnDiag = Diags.getCustomDiagID(
650 DiagnosticsEngine::Warning,
651 "rewriter doesn't support user-specified control flow semantics "
652 "for @try/@finally (code may not execute properly)");
653}
654
655ASTConsumer *clang::CreateModernObjCRewriter(const std::string& InFile,
656 raw_ostream* OS,
657 DiagnosticsEngine &Diags,
658 const LangOptions &LOpts,
Fariborz Jahanianada71912013-02-08 00:27:34 +0000659 bool SilenceRewriteMacroWarning,
660 bool LineInfo) {
661 return new RewriteModernObjC(InFile, OS, Diags, LOpts,
662 SilenceRewriteMacroWarning, LineInfo);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000663}
664
665void RewriteModernObjC::InitializeCommon(ASTContext &context) {
666 Context = &context;
667 SM = &Context->getSourceManager();
668 TUDecl = Context->getTranslationUnitDecl();
669 MsgSendFunctionDecl = 0;
670 MsgSendSuperFunctionDecl = 0;
671 MsgSendStretFunctionDecl = 0;
672 MsgSendSuperStretFunctionDecl = 0;
673 MsgSendFpretFunctionDecl = 0;
674 GetClassFunctionDecl = 0;
675 GetMetaClassFunctionDecl = 0;
676 GetSuperClassFunctionDecl = 0;
677 SelGetUidFunctionDecl = 0;
678 CFStringFunctionDecl = 0;
679 ConstantStringClassReference = 0;
680 NSStringRecord = 0;
681 CurMethodDef = 0;
682 CurFunctionDef = 0;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000683 GlobalVarDecl = 0;
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +0000684 GlobalConstructionExp = 0;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000685 SuperStructDecl = 0;
686 ProtocolTypeDecl = 0;
687 ConstantStringDecl = 0;
688 BcLabelCount = 0;
689 SuperContructorFunctionDecl = 0;
690 NumObjCStringLiterals = 0;
691 PropParentMap = 0;
692 CurrentBody = 0;
693 DisableReplaceStmt = false;
694 objc_impl_method = false;
695
696 // Get the ID and start/end of the main file.
697 MainFileID = SM->getMainFileID();
698 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
699 MainFileStart = MainBuf->getBufferStart();
700 MainFileEnd = MainBuf->getBufferEnd();
701
David Blaikie4e4d0842012-03-11 07:00:24 +0000702 Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOpts());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000703}
704
705//===----------------------------------------------------------------------===//
706// Top Level Driver Code
707//===----------------------------------------------------------------------===//
708
709void RewriteModernObjC::HandleTopLevelSingleDecl(Decl *D) {
710 if (Diags.hasErrorOccurred())
711 return;
712
713 // Two cases: either the decl could be in the main file, or it could be in a
714 // #included file. If the former, rewrite it now. If the later, check to see
715 // if we rewrote the #include/#import.
716 SourceLocation Loc = D->getLocation();
717 Loc = SM->getExpansionLoc(Loc);
718
719 // If this is for a builtin, ignore it.
720 if (Loc.isInvalid()) return;
721
722 // Look for built-in declarations that we need to refer during the rewrite.
723 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
724 RewriteFunctionDecl(FD);
725 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
726 // declared in <Foundation/NSString.h>
727 if (FVD->getName() == "_NSConstantStringClassReference") {
728 ConstantStringClassReference = FVD;
729 return;
730 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000731 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
732 RewriteCategoryDecl(CD);
733 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
734 if (PD->isThisDeclarationADefinition())
735 RewriteProtocolDecl(PD);
736 } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
Fariborz Jahanian8e86b2d2012-04-04 17:16:15 +0000737 // FIXME. This will not work in all situations and leaving it out
738 // is harmless.
739 // RewriteLinkageSpec(LSD);
740
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000741 // Recurse into linkage specifications
742 for (DeclContext::decl_iterator DI = LSD->decls_begin(),
743 DIEnd = LSD->decls_end();
744 DI != DIEnd; ) {
745 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>((*DI))) {
746 if (!IFace->isThisDeclarationADefinition()) {
747 SmallVector<Decl *, 8> DG;
748 SourceLocation StartLoc = IFace->getLocStart();
749 do {
750 if (isa<ObjCInterfaceDecl>(*DI) &&
751 !cast<ObjCInterfaceDecl>(*DI)->isThisDeclarationADefinition() &&
752 StartLoc == (*DI)->getLocStart())
753 DG.push_back(*DI);
754 else
755 break;
756
757 ++DI;
758 } while (DI != DIEnd);
759 RewriteForwardClassDecl(DG);
760 continue;
761 }
Fariborz Jahanianb3f904f2012-04-03 17:35:38 +0000762 else {
763 // Keep track of all interface declarations seen.
764 ObjCInterfacesSeen.push_back(IFace);
765 ++DI;
766 continue;
767 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000768 }
769
770 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>((*DI))) {
771 if (!Proto->isThisDeclarationADefinition()) {
772 SmallVector<Decl *, 8> DG;
773 SourceLocation StartLoc = Proto->getLocStart();
774 do {
775 if (isa<ObjCProtocolDecl>(*DI) &&
776 !cast<ObjCProtocolDecl>(*DI)->isThisDeclarationADefinition() &&
777 StartLoc == (*DI)->getLocStart())
778 DG.push_back(*DI);
779 else
780 break;
781
782 ++DI;
783 } while (DI != DIEnd);
784 RewriteForwardProtocolDecl(DG);
785 continue;
786 }
787 }
788
789 HandleTopLevelSingleDecl(*DI);
790 ++DI;
791 }
792 }
793 // If we have a decl in the main file, see if we should rewrite it.
794 if (SM->isFromMainFile(Loc))
795 return HandleDeclInMainFile(D);
796}
797
798//===----------------------------------------------------------------------===//
799// Syntactic (non-AST) Rewriting Code
800//===----------------------------------------------------------------------===//
801
802void RewriteModernObjC::RewriteInclude() {
803 SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
804 StringRef MainBuf = SM->getBufferData(MainFileID);
805 const char *MainBufStart = MainBuf.begin();
806 const char *MainBufEnd = MainBuf.end();
807 size_t ImportLen = strlen("import");
808
809 // Loop over the whole file, looking for includes.
810 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
811 if (*BufPtr == '#') {
812 if (++BufPtr == MainBufEnd)
813 return;
814 while (*BufPtr == ' ' || *BufPtr == '\t')
815 if (++BufPtr == MainBufEnd)
816 return;
817 if (!strncmp(BufPtr, "import", ImportLen)) {
818 // replace import with include
819 SourceLocation ImportLoc =
820 LocStart.getLocWithOffset(BufPtr-MainBufStart);
821 ReplaceText(ImportLoc, ImportLen, "include");
822 BufPtr += ImportLen;
823 }
824 }
825 }
826}
827
Fariborz Jahanian163d3ce2012-05-08 23:54:35 +0000828static void WriteInternalIvarName(const ObjCInterfaceDecl *IDecl,
829 ObjCIvarDecl *IvarDecl, std::string &Result) {
830 Result += "OBJC_IVAR_$_";
831 Result += IDecl->getName();
832 Result += "$";
833 Result += IvarDecl->getName();
834}
835
836std::string
837RewriteModernObjC::getIvarAccessString(ObjCIvarDecl *D) {
838 const ObjCInterfaceDecl *ClassDecl = D->getContainingInterface();
839
840 // Build name of symbol holding ivar offset.
841 std::string IvarOffsetName;
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +0000842 if (D->isBitField())
843 ObjCIvarBitfieldGroupOffset(D, IvarOffsetName);
844 else
845 WriteInternalIvarName(ClassDecl, D, IvarOffsetName);
Fariborz Jahanian163d3ce2012-05-08 23:54:35 +0000846
847
848 std::string S = "(*(";
849 QualType IvarT = D->getType();
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +0000850 if (D->isBitField())
851 IvarT = GetGroupRecordTypeForObjCIvarBitfield(D);
Fariborz Jahanian163d3ce2012-05-08 23:54:35 +0000852
853 if (!isa<TypedefType>(IvarT) && IvarT->isRecordType()) {
854 RecordDecl *RD = IvarT->getAs<RecordType>()->getDecl();
855 RD = RD->getDefinition();
856 if (RD && !RD->getDeclName().getAsIdentifierInfo()) {
857 // decltype(((Foo_IMPL*)0)->bar) *
858 ObjCContainerDecl *CDecl =
859 dyn_cast<ObjCContainerDecl>(D->getDeclContext());
860 // ivar in class extensions requires special treatment.
861 if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(CDecl))
862 CDecl = CatDecl->getClassInterface();
863 std::string RecName = CDecl->getName();
864 RecName += "_IMPL";
865 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
866 SourceLocation(), SourceLocation(),
867 &Context->Idents.get(RecName.c_str()));
868 QualType PtrStructIMPL = Context->getPointerType(Context->getTagDeclType(RD));
869 unsigned UnsignedIntSize =
870 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
871 Expr *Zero = IntegerLiteral::Create(*Context,
872 llvm::APInt(UnsignedIntSize, 0),
873 Context->UnsignedIntTy, SourceLocation());
874 Zero = NoTypeInfoCStyleCastExpr(Context, PtrStructIMPL, CK_BitCast, Zero);
875 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
876 Zero);
877 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
878 SourceLocation(),
879 &Context->Idents.get(D->getNameAsString()),
880 IvarT, 0,
881 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smithca523302012-06-10 03:12:00 +0000882 ICIS_NoInit);
Fariborz Jahanian163d3ce2012-05-08 23:54:35 +0000883 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
884 FD->getType(), VK_LValue,
885 OK_Ordinary);
886 IvarT = Context->getDecltypeType(ME, ME->getType());
887 }
888 }
889 convertObjCTypeToCStyleType(IvarT);
890 QualType castT = Context->getPointerType(IvarT);
891 std::string TypeString(castT.getAsString(Context->getPrintingPolicy()));
892 S += TypeString;
893 S += ")";
894
895 // ((char *)self + IVAR_OFFSET_SYMBOL_NAME)
896 S += "((char *)self + ";
897 S += IvarOffsetName;
898 S += "))";
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +0000899 if (D->isBitField()) {
900 S += ".";
901 S += D->getNameAsString();
902 }
Fariborz Jahanian163d3ce2012-05-08 23:54:35 +0000903 ReferencedIvars[const_cast<ObjCInterfaceDecl *>(ClassDecl)].insert(D);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000904 return S;
905}
906
Fariborz Jahanian301e2e42012-05-03 22:52:13 +0000907/// mustSynthesizeSetterGetterMethod - returns true if setter or getter has not
908/// been found in the class implementation. In this case, it must be synthesized.
909static bool mustSynthesizeSetterGetterMethod(ObjCImplementationDecl *IMP,
910 ObjCPropertyDecl *PD,
911 bool getter) {
912 return getter ? !IMP->getInstanceMethod(PD->getGetterName())
913 : !IMP->getInstanceMethod(PD->getSetterName());
914
915}
916
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000917void RewriteModernObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
918 ObjCImplementationDecl *IMD,
919 ObjCCategoryImplDecl *CID) {
920 static bool objcGetPropertyDefined = false;
921 static bool objcSetPropertyDefined = false;
Fariborz Jahanian301e2e42012-05-03 22:52:13 +0000922 SourceLocation startGetterSetterLoc;
923
924 if (PID->getLocStart().isValid()) {
925 SourceLocation startLoc = PID->getLocStart();
926 InsertText(startLoc, "// ");
927 const char *startBuf = SM->getCharacterData(startLoc);
928 assert((*startBuf == '@') && "bogus @synthesize location");
929 const char *semiBuf = strchr(startBuf, ';');
930 assert((*semiBuf == ';') && "@synthesize: can't find ';'");
931 startGetterSetterLoc = startLoc.getLocWithOffset(semiBuf-startBuf+1);
932 }
933 else
934 startGetterSetterLoc = IMD ? IMD->getLocEnd() : CID->getLocEnd();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000935
936 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
937 return; // FIXME: is this correct?
938
939 // Generate the 'getter' function.
940 ObjCPropertyDecl *PD = PID->getPropertyDecl();
941 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
942
943 if (!OID)
944 return;
Bill Wendlingad017fa2012-12-20 19:22:21 +0000945 unsigned Attributes = PD->getPropertyAttributes();
Fariborz Jahanian301e2e42012-05-03 22:52:13 +0000946 if (mustSynthesizeSetterGetterMethod(IMD, PD, true /*getter*/)) {
Bill Wendlingad017fa2012-12-20 19:22:21 +0000947 bool GenGetProperty = !(Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic) &&
948 (Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000949 ObjCPropertyDecl::OBJC_PR_copy));
950 std::string Getr;
951 if (GenGetProperty && !objcGetPropertyDefined) {
952 objcGetPropertyDefined = true;
953 // FIXME. Is this attribute correct in all cases?
954 Getr = "\nextern \"C\" __declspec(dllimport) "
955 "id objc_getProperty(id, SEL, long, bool);\n";
956 }
957 RewriteObjCMethodDecl(OID->getContainingInterface(),
958 PD->getGetterMethodDecl(), Getr);
959 Getr += "{ ";
960 // Synthesize an explicit cast to gain access to the ivar.
961 // See objc-act.c:objc_synthesize_new_getter() for details.
962 if (GenGetProperty) {
963 // return objc_getProperty(self, _cmd, offsetof(ClassDecl, OID), 1)
964 Getr += "typedef ";
965 const FunctionType *FPRetType = 0;
966 RewriteTypeIntoString(PD->getGetterMethodDecl()->getResultType(), Getr,
967 FPRetType);
968 Getr += " _TYPE";
969 if (FPRetType) {
970 Getr += ")"; // close the precedence "scope" for "*".
971
972 // Now, emit the argument types (if any).
973 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)){
974 Getr += "(";
975 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
976 if (i) Getr += ", ";
977 std::string ParamStr = FT->getArgType(i).getAsString(
978 Context->getPrintingPolicy());
979 Getr += ParamStr;
980 }
981 if (FT->isVariadic()) {
982 if (FT->getNumArgs()) Getr += ", ";
983 Getr += "...";
984 }
985 Getr += ")";
986 } else
987 Getr += "()";
988 }
989 Getr += ";\n";
990 Getr += "return (_TYPE)";
991 Getr += "objc_getProperty(self, _cmd, ";
992 RewriteIvarOffsetComputation(OID, Getr);
993 Getr += ", 1)";
994 }
995 else
996 Getr += "return " + getIvarAccessString(OID);
997 Getr += "; }";
Fariborz Jahanian301e2e42012-05-03 22:52:13 +0000998 InsertText(startGetterSetterLoc, Getr);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000999 }
1000
Fariborz Jahanian301e2e42012-05-03 22:52:13 +00001001 if (PD->isReadOnly() ||
1002 !mustSynthesizeSetterGetterMethod(IMD, PD, false /*setter*/))
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001003 return;
1004
1005 // Generate the 'setter' function.
1006 std::string Setr;
Bill Wendlingad017fa2012-12-20 19:22:21 +00001007 bool GenSetProperty = Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001008 ObjCPropertyDecl::OBJC_PR_copy);
1009 if (GenSetProperty && !objcSetPropertyDefined) {
1010 objcSetPropertyDefined = true;
1011 // FIXME. Is this attribute correct in all cases?
1012 Setr = "\nextern \"C\" __declspec(dllimport) "
1013 "void objc_setProperty (id, SEL, long, id, bool, bool);\n";
1014 }
1015
1016 RewriteObjCMethodDecl(OID->getContainingInterface(),
1017 PD->getSetterMethodDecl(), Setr);
1018 Setr += "{ ";
1019 // Synthesize an explicit cast to initialize the ivar.
1020 // See objc-act.c:objc_synthesize_new_setter() for details.
1021 if (GenSetProperty) {
1022 Setr += "objc_setProperty (self, _cmd, ";
1023 RewriteIvarOffsetComputation(OID, Setr);
1024 Setr += ", (id)";
1025 Setr += PD->getName();
1026 Setr += ", ";
Bill Wendlingad017fa2012-12-20 19:22:21 +00001027 if (Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic)
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001028 Setr += "0, ";
1029 else
1030 Setr += "1, ";
Bill Wendlingad017fa2012-12-20 19:22:21 +00001031 if (Attributes & ObjCPropertyDecl::OBJC_PR_copy)
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001032 Setr += "1)";
1033 else
1034 Setr += "0)";
1035 }
1036 else {
1037 Setr += getIvarAccessString(OID) + " = ";
1038 Setr += PD->getName();
1039 }
Fariborz Jahanian301e2e42012-05-03 22:52:13 +00001040 Setr += "; }\n";
1041 InsertText(startGetterSetterLoc, Setr);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001042}
1043
1044static void RewriteOneForwardClassDecl(ObjCInterfaceDecl *ForwardDecl,
1045 std::string &typedefString) {
Fariborz Jahanianbfaa1112013-02-08 17:15:07 +00001046 typedefString += "\n#ifndef _REWRITER_typedef_";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001047 typedefString += ForwardDecl->getNameAsString();
1048 typedefString += "\n";
1049 typedefString += "#define _REWRITER_typedef_";
1050 typedefString += ForwardDecl->getNameAsString();
1051 typedefString += "\n";
1052 typedefString += "typedef struct objc_object ";
1053 typedefString += ForwardDecl->getNameAsString();
Fariborz Jahanianc38503b2012-03-12 23:58:28 +00001054 // typedef struct { } _objc_exc_Classname;
1055 typedefString += ";\ntypedef struct {} _objc_exc_";
1056 typedefString += ForwardDecl->getNameAsString();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001057 typedefString += ";\n#endif\n";
1058}
1059
1060void RewriteModernObjC::RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
1061 const std::string &typedefString) {
1062 SourceLocation startLoc = ClassDecl->getLocStart();
1063 const char *startBuf = SM->getCharacterData(startLoc);
1064 const char *semiPtr = strchr(startBuf, ';');
1065 // Replace the @class with typedefs corresponding to the classes.
1066 ReplaceText(startLoc, semiPtr-startBuf+1, typedefString);
1067}
1068
1069void RewriteModernObjC::RewriteForwardClassDecl(DeclGroupRef D) {
1070 std::string typedefString;
1071 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
1072 ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(*I);
1073 if (I == D.begin()) {
1074 // Translate to typedef's that forward reference structs with the same name
1075 // as the class. As a convenience, we include the original declaration
1076 // as a comment.
1077 typedefString += "// @class ";
1078 typedefString += ForwardDecl->getNameAsString();
Fariborz Jahanianbfaa1112013-02-08 17:15:07 +00001079 typedefString += ";";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001080 }
1081 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
1082 }
1083 DeclGroupRef::iterator I = D.begin();
1084 RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(*I), typedefString);
1085}
1086
1087void RewriteModernObjC::RewriteForwardClassDecl(
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001088 const SmallVector<Decl *, 8> &D) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001089 std::string typedefString;
1090 for (unsigned i = 0; i < D.size(); i++) {
1091 ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(D[i]);
1092 if (i == 0) {
1093 typedefString += "// @class ";
1094 typedefString += ForwardDecl->getNameAsString();
Fariborz Jahanianbfaa1112013-02-08 17:15:07 +00001095 typedefString += ";";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001096 }
1097 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
1098 }
1099 RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(D[0]), typedefString);
1100}
1101
1102void RewriteModernObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
1103 // When method is a synthesized one, such as a getter/setter there is
1104 // nothing to rewrite.
1105 if (Method->isImplicit())
1106 return;
1107 SourceLocation LocStart = Method->getLocStart();
1108 SourceLocation LocEnd = Method->getLocEnd();
1109
1110 if (SM->getExpansionLineNumber(LocEnd) >
1111 SM->getExpansionLineNumber(LocStart)) {
1112 InsertText(LocStart, "#if 0\n");
1113 ReplaceText(LocEnd, 1, ";\n#endif\n");
1114 } else {
1115 InsertText(LocStart, "// ");
1116 }
1117}
1118
1119void RewriteModernObjC::RewriteProperty(ObjCPropertyDecl *prop) {
1120 SourceLocation Loc = prop->getAtLoc();
1121
1122 ReplaceText(Loc, 0, "// ");
1123 // FIXME: handle properties that are declared across multiple lines.
1124}
1125
1126void RewriteModernObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
1127 SourceLocation LocStart = CatDecl->getLocStart();
1128
1129 // FIXME: handle category headers that are declared across multiple lines.
Fariborz Jahanianb68258f2012-05-01 17:46:45 +00001130 if (CatDecl->getIvarRBraceLoc().isValid()) {
1131 ReplaceText(LocStart, 1, "/** ");
1132 ReplaceText(CatDecl->getIvarRBraceLoc(), 1, "**/ ");
1133 }
1134 else {
Fariborz Jahaniand2aea122012-02-19 19:00:05 +00001135 ReplaceText(LocStart, 0, "// ");
Fariborz Jahanianb68258f2012-05-01 17:46:45 +00001136 }
Fariborz Jahanianaf300292012-02-20 20:09:20 +00001137
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001138 for (ObjCCategoryDecl::prop_iterator I = CatDecl->prop_begin(),
1139 E = CatDecl->prop_end(); I != E; ++I)
David Blaikie581deb32012-06-06 20:45:41 +00001140 RewriteProperty(*I);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001141
1142 for (ObjCCategoryDecl::instmeth_iterator
1143 I = CatDecl->instmeth_begin(), E = CatDecl->instmeth_end();
1144 I != E; ++I)
1145 RewriteMethodDeclaration(*I);
1146 for (ObjCCategoryDecl::classmeth_iterator
1147 I = CatDecl->classmeth_begin(), E = CatDecl->classmeth_end();
1148 I != E; ++I)
1149 RewriteMethodDeclaration(*I);
1150
1151 // Lastly, comment out the @end.
1152 ReplaceText(CatDecl->getAtEndRange().getBegin(),
1153 strlen("@end"), "/* @end */");
1154}
1155
1156void RewriteModernObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
1157 SourceLocation LocStart = PDecl->getLocStart();
1158 assert(PDecl->isThisDeclarationADefinition());
1159
1160 // FIXME: handle protocol headers that are declared across multiple lines.
1161 ReplaceText(LocStart, 0, "// ");
1162
1163 for (ObjCProtocolDecl::instmeth_iterator
1164 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
1165 I != E; ++I)
1166 RewriteMethodDeclaration(*I);
1167 for (ObjCProtocolDecl::classmeth_iterator
1168 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
1169 I != E; ++I)
1170 RewriteMethodDeclaration(*I);
1171
1172 for (ObjCInterfaceDecl::prop_iterator I = PDecl->prop_begin(),
1173 E = PDecl->prop_end(); I != E; ++I)
David Blaikie581deb32012-06-06 20:45:41 +00001174 RewriteProperty(*I);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001175
1176 // Lastly, comment out the @end.
1177 SourceLocation LocEnd = PDecl->getAtEndRange().getBegin();
1178 ReplaceText(LocEnd, strlen("@end"), "/* @end */");
1179
1180 // Must comment out @optional/@required
1181 const char *startBuf = SM->getCharacterData(LocStart);
1182 const char *endBuf = SM->getCharacterData(LocEnd);
1183 for (const char *p = startBuf; p < endBuf; p++) {
1184 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
1185 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
1186 ReplaceText(OptionalLoc, strlen("@optional"), "/* @optional */");
1187
1188 }
1189 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
1190 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
1191 ReplaceText(OptionalLoc, strlen("@required"), "/* @required */");
1192
1193 }
1194 }
1195}
1196
1197void RewriteModernObjC::RewriteForwardProtocolDecl(DeclGroupRef D) {
1198 SourceLocation LocStart = (*D.begin())->getLocStart();
1199 if (LocStart.isInvalid())
1200 llvm_unreachable("Invalid SourceLocation");
1201 // FIXME: handle forward protocol that are declared across multiple lines.
1202 ReplaceText(LocStart, 0, "// ");
1203}
1204
1205void
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001206RewriteModernObjC::RewriteForwardProtocolDecl(const SmallVector<Decl *, 8> &DG) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001207 SourceLocation LocStart = DG[0]->getLocStart();
1208 if (LocStart.isInvalid())
1209 llvm_unreachable("Invalid SourceLocation");
1210 // FIXME: handle forward protocol that are declared across multiple lines.
1211 ReplaceText(LocStart, 0, "// ");
1212}
1213
Fariborz Jahanianb3f904f2012-04-03 17:35:38 +00001214void
1215RewriteModernObjC::RewriteLinkageSpec(LinkageSpecDecl *LSD) {
1216 SourceLocation LocStart = LSD->getExternLoc();
1217 if (LocStart.isInvalid())
1218 llvm_unreachable("Invalid extern SourceLocation");
1219
1220 ReplaceText(LocStart, 0, "// ");
1221 if (!LSD->hasBraces())
1222 return;
1223 // FIXME. We don't rewrite well if '{' is not on same line as 'extern'.
1224 SourceLocation LocRBrace = LSD->getRBraceLoc();
1225 if (LocRBrace.isInvalid())
1226 llvm_unreachable("Invalid rbrace SourceLocation");
1227 ReplaceText(LocRBrace, 0, "// ");
1228}
1229
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001230void RewriteModernObjC::RewriteTypeIntoString(QualType T, std::string &ResultStr,
1231 const FunctionType *&FPRetType) {
1232 if (T->isObjCQualifiedIdType())
1233 ResultStr += "id";
1234 else if (T->isFunctionPointerType() ||
1235 T->isBlockPointerType()) {
1236 // needs special handling, since pointer-to-functions have special
1237 // syntax (where a decaration models use).
1238 QualType retType = T;
1239 QualType PointeeTy;
1240 if (const PointerType* PT = retType->getAs<PointerType>())
1241 PointeeTy = PT->getPointeeType();
1242 else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
1243 PointeeTy = BPT->getPointeeType();
1244 if ((FPRetType = PointeeTy->getAs<FunctionType>())) {
1245 ResultStr += FPRetType->getResultType().getAsString(
1246 Context->getPrintingPolicy());
1247 ResultStr += "(*";
1248 }
1249 } else
1250 ResultStr += T.getAsString(Context->getPrintingPolicy());
1251}
1252
1253void RewriteModernObjC::RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
1254 ObjCMethodDecl *OMD,
1255 std::string &ResultStr) {
1256 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
1257 const FunctionType *FPRetType = 0;
1258 ResultStr += "\nstatic ";
1259 RewriteTypeIntoString(OMD->getResultType(), ResultStr, FPRetType);
1260 ResultStr += " ";
1261
1262 // Unique method name
1263 std::string NameStr;
1264
1265 if (OMD->isInstanceMethod())
1266 NameStr += "_I_";
1267 else
1268 NameStr += "_C_";
1269
1270 NameStr += IDecl->getNameAsString();
1271 NameStr += "_";
1272
1273 if (ObjCCategoryImplDecl *CID =
1274 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
1275 NameStr += CID->getNameAsString();
1276 NameStr += "_";
1277 }
1278 // Append selector names, replacing ':' with '_'
1279 {
1280 std::string selString = OMD->getSelector().getAsString();
1281 int len = selString.size();
1282 for (int i = 0; i < len; i++)
1283 if (selString[i] == ':')
1284 selString[i] = '_';
1285 NameStr += selString;
1286 }
1287 // Remember this name for metadata emission
1288 MethodInternalNames[OMD] = NameStr;
1289 ResultStr += NameStr;
1290
1291 // Rewrite arguments
1292 ResultStr += "(";
1293
1294 // invisible arguments
1295 if (OMD->isInstanceMethod()) {
1296 QualType selfTy = Context->getObjCInterfaceType(IDecl);
1297 selfTy = Context->getPointerType(selfTy);
1298 if (!LangOpts.MicrosoftExt) {
1299 if (ObjCSynthesizedStructs.count(const_cast<ObjCInterfaceDecl*>(IDecl)))
1300 ResultStr += "struct ";
1301 }
1302 // When rewriting for Microsoft, explicitly omit the structure name.
1303 ResultStr += IDecl->getNameAsString();
1304 ResultStr += " *";
1305 }
1306 else
1307 ResultStr += Context->getObjCClassType().getAsString(
1308 Context->getPrintingPolicy());
1309
1310 ResultStr += " self, ";
1311 ResultStr += Context->getObjCSelType().getAsString(Context->getPrintingPolicy());
1312 ResultStr += " _cmd";
1313
1314 // Method arguments.
1315 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
1316 E = OMD->param_end(); PI != E; ++PI) {
1317 ParmVarDecl *PDecl = *PI;
1318 ResultStr += ", ";
1319 if (PDecl->getType()->isObjCQualifiedIdType()) {
1320 ResultStr += "id ";
1321 ResultStr += PDecl->getNameAsString();
1322 } else {
1323 std::string Name = PDecl->getNameAsString();
1324 QualType QT = PDecl->getType();
1325 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian2610f902012-03-27 16:42:20 +00001326 (void)convertBlockPointerToFunctionPointer(QT);
1327 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001328 ResultStr += Name;
1329 }
1330 }
1331 if (OMD->isVariadic())
1332 ResultStr += ", ...";
1333 ResultStr += ") ";
1334
1335 if (FPRetType) {
1336 ResultStr += ")"; // close the precedence "scope" for "*".
1337
1338 // Now, emit the argument types (if any).
1339 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
1340 ResultStr += "(";
1341 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
1342 if (i) ResultStr += ", ";
1343 std::string ParamStr = FT->getArgType(i).getAsString(
1344 Context->getPrintingPolicy());
1345 ResultStr += ParamStr;
1346 }
1347 if (FT->isVariadic()) {
1348 if (FT->getNumArgs()) ResultStr += ", ";
1349 ResultStr += "...";
1350 }
1351 ResultStr += ")";
1352 } else {
1353 ResultStr += "()";
1354 }
1355 }
1356}
1357void RewriteModernObjC::RewriteImplementationDecl(Decl *OID) {
1358 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
1359 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
1360
Fariborz Jahaniand2aea122012-02-19 19:00:05 +00001361 if (IMD) {
Fariborz Jahanianb68258f2012-05-01 17:46:45 +00001362 if (IMD->getIvarRBraceLoc().isValid()) {
1363 ReplaceText(IMD->getLocStart(), 1, "/** ");
1364 ReplaceText(IMD->getIvarRBraceLoc(), 1, "**/ ");
Fariborz Jahaniand2aea122012-02-19 19:00:05 +00001365 }
Fariborz Jahanianb68258f2012-05-01 17:46:45 +00001366 else {
1367 InsertText(IMD->getLocStart(), "// ");
1368 }
Fariborz Jahaniand2aea122012-02-19 19:00:05 +00001369 }
1370 else
1371 InsertText(CID->getLocStart(), "// ");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001372
1373 for (ObjCCategoryImplDecl::instmeth_iterator
1374 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
1375 E = IMD ? IMD->instmeth_end() : CID->instmeth_end();
1376 I != E; ++I) {
1377 std::string ResultStr;
1378 ObjCMethodDecl *OMD = *I;
1379 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
1380 SourceLocation LocStart = OMD->getLocStart();
1381 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
1382
1383 const char *startBuf = SM->getCharacterData(LocStart);
1384 const char *endBuf = SM->getCharacterData(LocEnd);
1385 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
1386 }
1387
1388 for (ObjCCategoryImplDecl::classmeth_iterator
1389 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
1390 E = IMD ? IMD->classmeth_end() : CID->classmeth_end();
1391 I != E; ++I) {
1392 std::string ResultStr;
1393 ObjCMethodDecl *OMD = *I;
1394 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
1395 SourceLocation LocStart = OMD->getLocStart();
1396 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
1397
1398 const char *startBuf = SM->getCharacterData(LocStart);
1399 const char *endBuf = SM->getCharacterData(LocEnd);
1400 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
1401 }
1402 for (ObjCCategoryImplDecl::propimpl_iterator
1403 I = IMD ? IMD->propimpl_begin() : CID->propimpl_begin(),
1404 E = IMD ? IMD->propimpl_end() : CID->propimpl_end();
1405 I != E; ++I) {
David Blaikie581deb32012-06-06 20:45:41 +00001406 RewritePropertyImplDecl(*I, IMD, CID);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001407 }
1408
1409 InsertText(IMD ? IMD->getLocEnd() : CID->getLocEnd(), "// ");
1410}
1411
1412void RewriteModernObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00001413 // Do not synthesize more than once.
1414 if (ObjCSynthesizedStructs.count(ClassDecl))
1415 return;
1416 // Make sure super class's are written before current class is written.
1417 ObjCInterfaceDecl *SuperClass = ClassDecl->getSuperClass();
1418 while (SuperClass) {
1419 RewriteInterfaceDecl(SuperClass);
1420 SuperClass = SuperClass->getSuperClass();
1421 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001422 std::string ResultStr;
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +00001423 if (!ObjCWrittenInterfaces.count(ClassDecl->getCanonicalDecl())) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001424 // we haven't seen a forward decl - generate a typedef.
Fariborz Jahanianc38503b2012-03-12 23:58:28 +00001425 RewriteOneForwardClassDecl(ClassDecl, ResultStr);
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00001426 RewriteIvarOffsetSymbols(ClassDecl, ResultStr);
1427
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001428 RewriteObjCInternalStruct(ClassDecl, ResultStr);
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +00001429 // Mark this typedef as having been written into its c++ equivalent.
1430 ObjCWrittenInterfaces.insert(ClassDecl->getCanonicalDecl());
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001431
1432 for (ObjCInterfaceDecl::prop_iterator I = ClassDecl->prop_begin(),
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001433 E = ClassDecl->prop_end(); I != E; ++I)
David Blaikie581deb32012-06-06 20:45:41 +00001434 RewriteProperty(*I);
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001435 for (ObjCInterfaceDecl::instmeth_iterator
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001436 I = ClassDecl->instmeth_begin(), E = ClassDecl->instmeth_end();
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001437 I != E; ++I)
1438 RewriteMethodDeclaration(*I);
1439 for (ObjCInterfaceDecl::classmeth_iterator
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001440 I = ClassDecl->classmeth_begin(), E = ClassDecl->classmeth_end();
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001441 I != E; ++I)
1442 RewriteMethodDeclaration(*I);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001443
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001444 // Lastly, comment out the @end.
1445 ReplaceText(ClassDecl->getAtEndRange().getBegin(), strlen("@end"),
1446 "/* @end */");
1447 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001448}
1449
1450Stmt *RewriteModernObjC::RewritePropertyOrImplicitSetter(PseudoObjectExpr *PseudoOp) {
1451 SourceRange OldRange = PseudoOp->getSourceRange();
1452
1453 // We just magically know some things about the structure of this
1454 // expression.
1455 ObjCMessageExpr *OldMsg =
1456 cast<ObjCMessageExpr>(PseudoOp->getSemanticExpr(
1457 PseudoOp->getNumSemanticExprs() - 1));
1458
1459 // Because the rewriter doesn't allow us to rewrite rewritten code,
1460 // we need to suppress rewriting the sub-statements.
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001461 Expr *Base;
1462 SmallVector<Expr*, 2> Args;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001463 {
1464 DisableReplaceStmtScope S(*this);
1465
1466 // Rebuild the base expression if we have one.
1467 Base = 0;
1468 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1469 Base = OldMsg->getInstanceReceiver();
1470 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1471 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1472 }
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001473
1474 unsigned numArgs = OldMsg->getNumArgs();
1475 for (unsigned i = 0; i < numArgs; i++) {
1476 Expr *Arg = OldMsg->getArg(i);
1477 if (isa<OpaqueValueExpr>(Arg))
1478 Arg = cast<OpaqueValueExpr>(Arg)->getSourceExpr();
1479 Arg = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Arg));
1480 Args.push_back(Arg);
1481 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001482 }
1483
1484 // TODO: avoid this copy.
1485 SmallVector<SourceLocation, 1> SelLocs;
1486 OldMsg->getSelectorLocs(SelLocs);
1487
1488 ObjCMessageExpr *NewMsg = 0;
1489 switch (OldMsg->getReceiverKind()) {
1490 case ObjCMessageExpr::Class:
1491 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1492 OldMsg->getValueKind(),
1493 OldMsg->getLeftLoc(),
1494 OldMsg->getClassReceiverTypeInfo(),
1495 OldMsg->getSelector(),
1496 SelLocs,
1497 OldMsg->getMethodDecl(),
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001498 Args,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001499 OldMsg->getRightLoc(),
1500 OldMsg->isImplicit());
1501 break;
1502
1503 case ObjCMessageExpr::Instance:
1504 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1505 OldMsg->getValueKind(),
1506 OldMsg->getLeftLoc(),
1507 Base,
1508 OldMsg->getSelector(),
1509 SelLocs,
1510 OldMsg->getMethodDecl(),
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001511 Args,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001512 OldMsg->getRightLoc(),
1513 OldMsg->isImplicit());
1514 break;
1515
1516 case ObjCMessageExpr::SuperClass:
1517 case ObjCMessageExpr::SuperInstance:
1518 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1519 OldMsg->getValueKind(),
1520 OldMsg->getLeftLoc(),
1521 OldMsg->getSuperLoc(),
1522 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1523 OldMsg->getSuperType(),
1524 OldMsg->getSelector(),
1525 SelLocs,
1526 OldMsg->getMethodDecl(),
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001527 Args,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001528 OldMsg->getRightLoc(),
1529 OldMsg->isImplicit());
1530 break;
1531 }
1532
1533 Stmt *Replacement = SynthMessageExpr(NewMsg);
1534 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1535 return Replacement;
1536}
1537
1538Stmt *RewriteModernObjC::RewritePropertyOrImplicitGetter(PseudoObjectExpr *PseudoOp) {
1539 SourceRange OldRange = PseudoOp->getSourceRange();
1540
1541 // We just magically know some things about the structure of this
1542 // expression.
1543 ObjCMessageExpr *OldMsg =
1544 cast<ObjCMessageExpr>(PseudoOp->getResultExpr()->IgnoreImplicit());
1545
1546 // Because the rewriter doesn't allow us to rewrite rewritten code,
1547 // we need to suppress rewriting the sub-statements.
1548 Expr *Base = 0;
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001549 SmallVector<Expr*, 1> Args;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001550 {
1551 DisableReplaceStmtScope S(*this);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001552 // Rebuild the base expression if we have one.
1553 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1554 Base = OldMsg->getInstanceReceiver();
1555 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1556 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1557 }
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001558 unsigned numArgs = OldMsg->getNumArgs();
1559 for (unsigned i = 0; i < numArgs; i++) {
1560 Expr *Arg = OldMsg->getArg(i);
1561 if (isa<OpaqueValueExpr>(Arg))
1562 Arg = cast<OpaqueValueExpr>(Arg)->getSourceExpr();
1563 Arg = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Arg));
1564 Args.push_back(Arg);
1565 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001566 }
1567
1568 // Intentionally empty.
1569 SmallVector<SourceLocation, 1> SelLocs;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001570
1571 ObjCMessageExpr *NewMsg = 0;
1572 switch (OldMsg->getReceiverKind()) {
1573 case ObjCMessageExpr::Class:
1574 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1575 OldMsg->getValueKind(),
1576 OldMsg->getLeftLoc(),
1577 OldMsg->getClassReceiverTypeInfo(),
1578 OldMsg->getSelector(),
1579 SelLocs,
1580 OldMsg->getMethodDecl(),
1581 Args,
1582 OldMsg->getRightLoc(),
1583 OldMsg->isImplicit());
1584 break;
1585
1586 case ObjCMessageExpr::Instance:
1587 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1588 OldMsg->getValueKind(),
1589 OldMsg->getLeftLoc(),
1590 Base,
1591 OldMsg->getSelector(),
1592 SelLocs,
1593 OldMsg->getMethodDecl(),
1594 Args,
1595 OldMsg->getRightLoc(),
1596 OldMsg->isImplicit());
1597 break;
1598
1599 case ObjCMessageExpr::SuperClass:
1600 case ObjCMessageExpr::SuperInstance:
1601 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1602 OldMsg->getValueKind(),
1603 OldMsg->getLeftLoc(),
1604 OldMsg->getSuperLoc(),
1605 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1606 OldMsg->getSuperType(),
1607 OldMsg->getSelector(),
1608 SelLocs,
1609 OldMsg->getMethodDecl(),
1610 Args,
1611 OldMsg->getRightLoc(),
1612 OldMsg->isImplicit());
1613 break;
1614 }
1615
1616 Stmt *Replacement = SynthMessageExpr(NewMsg);
1617 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1618 return Replacement;
1619}
1620
1621/// SynthCountByEnumWithState - To print:
1622/// ((unsigned int (*)
1623/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1624/// (void *)objc_msgSend)((id)l_collection,
1625/// sel_registerName(
1626/// "countByEnumeratingWithState:objects:count:"),
1627/// &enumState,
1628/// (id *)__rw_items, (unsigned int)16)
1629///
1630void RewriteModernObjC::SynthCountByEnumWithState(std::string &buf) {
1631 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1632 "id *, unsigned int))(void *)objc_msgSend)";
1633 buf += "\n\t\t";
1634 buf += "((id)l_collection,\n\t\t";
1635 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1636 buf += "\n\t\t";
1637 buf += "&enumState, "
1638 "(id *)__rw_items, (unsigned int)16)";
1639}
1640
1641/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1642/// statement to exit to its outer synthesized loop.
1643///
1644Stmt *RewriteModernObjC::RewriteBreakStmt(BreakStmt *S) {
1645 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1646 return S;
1647 // replace break with goto __break_label
1648 std::string buf;
1649
1650 SourceLocation startLoc = S->getLocStart();
1651 buf = "goto __break_label_";
1652 buf += utostr(ObjCBcLabelNo.back());
1653 ReplaceText(startLoc, strlen("break"), buf);
1654
1655 return 0;
1656}
1657
Fariborz Jahanianf616ae22012-11-06 23:25:49 +00001658void RewriteModernObjC::ConvertSourceLocationToLineDirective(
1659 SourceLocation Loc,
1660 std::string &LineString) {
Fariborz Jahanianada71912013-02-08 00:27:34 +00001661 if (Loc.isFileID() && GenerateLineInfo) {
Fariborz Jahanianf616ae22012-11-06 23:25:49 +00001662 LineString += "\n#line ";
1663 PresumedLoc PLoc = SM->getPresumedLoc(Loc);
1664 LineString += utostr(PLoc.getLine());
1665 LineString += " \"";
1666 LineString += Lexer::Stringify(PLoc.getFilename());
1667 LineString += "\"\n";
1668 }
1669}
1670
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001671/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1672/// statement to continue with its inner synthesized loop.
1673///
1674Stmt *RewriteModernObjC::RewriteContinueStmt(ContinueStmt *S) {
1675 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1676 return S;
1677 // replace continue with goto __continue_label
1678 std::string buf;
1679
1680 SourceLocation startLoc = S->getLocStart();
1681 buf = "goto __continue_label_";
1682 buf += utostr(ObjCBcLabelNo.back());
1683 ReplaceText(startLoc, strlen("continue"), buf);
1684
1685 return 0;
1686}
1687
1688/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
1689/// It rewrites:
1690/// for ( type elem in collection) { stmts; }
1691
1692/// Into:
1693/// {
1694/// type elem;
1695/// struct __objcFastEnumerationState enumState = { 0 };
1696/// id __rw_items[16];
1697/// id l_collection = (id)collection;
1698/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1699/// objects:__rw_items count:16];
1700/// if (limit) {
1701/// unsigned long startMutations = *enumState.mutationsPtr;
1702/// do {
1703/// unsigned long counter = 0;
1704/// do {
1705/// if (startMutations != *enumState.mutationsPtr)
1706/// objc_enumerationMutation(l_collection);
1707/// elem = (type)enumState.itemsPtr[counter++];
1708/// stmts;
1709/// __continue_label: ;
1710/// } while (counter < limit);
1711/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1712/// objects:__rw_items count:16]);
1713/// elem = nil;
1714/// __break_label: ;
1715/// }
1716/// else
1717/// elem = nil;
1718/// }
1719///
1720Stmt *RewriteModernObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
1721 SourceLocation OrigEnd) {
1722 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
1723 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
1724 "ObjCForCollectionStmt Statement stack mismatch");
1725 assert(!ObjCBcLabelNo.empty() &&
1726 "ObjCForCollectionStmt - Label No stack empty");
1727
1728 SourceLocation startLoc = S->getLocStart();
1729 const char *startBuf = SM->getCharacterData(startLoc);
1730 StringRef elementName;
1731 std::string elementTypeAsString;
1732 std::string buf;
Fariborz Jahanianf616ae22012-11-06 23:25:49 +00001733 // line directive first.
1734 SourceLocation ForEachLoc = S->getForLoc();
1735 ConvertSourceLocationToLineDirective(ForEachLoc, buf);
1736 buf += "{\n\t";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001737 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1738 // type elem;
1739 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
1740 QualType ElementType = cast<ValueDecl>(D)->getType();
1741 if (ElementType->isObjCQualifiedIdType() ||
1742 ElementType->isObjCQualifiedInterfaceType())
1743 // Simply use 'id' for all qualified types.
1744 elementTypeAsString = "id";
1745 else
1746 elementTypeAsString = ElementType.getAsString(Context->getPrintingPolicy());
1747 buf += elementTypeAsString;
1748 buf += " ";
1749 elementName = D->getName();
1750 buf += elementName;
1751 buf += ";\n\t";
1752 }
1753 else {
1754 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
1755 elementName = DR->getDecl()->getName();
1756 ValueDecl *VD = cast<ValueDecl>(DR->getDecl());
1757 if (VD->getType()->isObjCQualifiedIdType() ||
1758 VD->getType()->isObjCQualifiedInterfaceType())
1759 // Simply use 'id' for all qualified types.
1760 elementTypeAsString = "id";
1761 else
1762 elementTypeAsString = VD->getType().getAsString(Context->getPrintingPolicy());
1763 }
1764
1765 // struct __objcFastEnumerationState enumState = { 0 };
1766 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1767 // id __rw_items[16];
1768 buf += "id __rw_items[16];\n\t";
1769 // id l_collection = (id)
1770 buf += "id l_collection = (id)";
1771 // Find start location of 'collection' the hard way!
1772 const char *startCollectionBuf = startBuf;
1773 startCollectionBuf += 3; // skip 'for'
1774 startCollectionBuf = strchr(startCollectionBuf, '(');
1775 startCollectionBuf++; // skip '('
1776 // find 'in' and skip it.
1777 while (*startCollectionBuf != ' ' ||
1778 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1779 (*(startCollectionBuf+3) != ' ' &&
1780 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1781 startCollectionBuf++;
1782 startCollectionBuf += 3;
1783
1784 // Replace: "for (type element in" with string constructed thus far.
1785 ReplaceText(startLoc, startCollectionBuf - startBuf, buf);
1786 // Replace ')' in for '(' type elem in collection ')' with ';'
1787 SourceLocation rightParenLoc = S->getRParenLoc();
1788 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1789 SourceLocation lparenLoc = startLoc.getLocWithOffset(rparenBuf-startBuf);
1790 buf = ";\n\t";
1791
1792 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1793 // objects:__rw_items count:16];
1794 // which is synthesized into:
1795 // unsigned int limit =
1796 // ((unsigned int (*)
1797 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1798 // (void *)objc_msgSend)((id)l_collection,
1799 // sel_registerName(
1800 // "countByEnumeratingWithState:objects:count:"),
1801 // (struct __objcFastEnumerationState *)&state,
1802 // (id *)__rw_items, (unsigned int)16);
1803 buf += "unsigned long limit =\n\t\t";
1804 SynthCountByEnumWithState(buf);
1805 buf += ";\n\t";
1806 /// if (limit) {
1807 /// unsigned long startMutations = *enumState.mutationsPtr;
1808 /// do {
1809 /// unsigned long counter = 0;
1810 /// do {
1811 /// if (startMutations != *enumState.mutationsPtr)
1812 /// objc_enumerationMutation(l_collection);
1813 /// elem = (type)enumState.itemsPtr[counter++];
1814 buf += "if (limit) {\n\t";
1815 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1816 buf += "do {\n\t\t";
1817 buf += "unsigned long counter = 0;\n\t\t";
1818 buf += "do {\n\t\t\t";
1819 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1820 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1821 buf += elementName;
1822 buf += " = (";
1823 buf += elementTypeAsString;
1824 buf += ")enumState.itemsPtr[counter++];";
1825 // Replace ')' in for '(' type elem in collection ')' with all of these.
1826 ReplaceText(lparenLoc, 1, buf);
1827
1828 /// __continue_label: ;
1829 /// } while (counter < limit);
1830 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1831 /// objects:__rw_items count:16]);
1832 /// elem = nil;
1833 /// __break_label: ;
1834 /// }
1835 /// else
1836 /// elem = nil;
1837 /// }
1838 ///
1839 buf = ";\n\t";
1840 buf += "__continue_label_";
1841 buf += utostr(ObjCBcLabelNo.back());
1842 buf += ": ;";
1843 buf += "\n\t\t";
1844 buf += "} while (counter < limit);\n\t";
1845 buf += "} while (limit = ";
1846 SynthCountByEnumWithState(buf);
1847 buf += ");\n\t";
1848 buf += elementName;
1849 buf += " = ((";
1850 buf += elementTypeAsString;
1851 buf += ")0);\n\t";
1852 buf += "__break_label_";
1853 buf += utostr(ObjCBcLabelNo.back());
1854 buf += ": ;\n\t";
1855 buf += "}\n\t";
1856 buf += "else\n\t\t";
1857 buf += elementName;
1858 buf += " = ((";
1859 buf += elementTypeAsString;
1860 buf += ")0);\n\t";
1861 buf += "}\n";
1862
1863 // Insert all these *after* the statement body.
1864 // FIXME: If this should support Obj-C++, support CXXTryStmt
1865 if (isa<CompoundStmt>(S->getBody())) {
1866 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(1);
1867 InsertText(endBodyLoc, buf);
1868 } else {
1869 /* Need to treat single statements specially. For example:
1870 *
1871 * for (A *a in b) if (stuff()) break;
1872 * for (A *a in b) xxxyy;
1873 *
1874 * The following code simply scans ahead to the semi to find the actual end.
1875 */
1876 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1877 const char *semiBuf = strchr(stmtBuf, ';');
1878 assert(semiBuf && "Can't find ';'");
1879 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(semiBuf-stmtBuf+1);
1880 InsertText(endBodyLoc, buf);
1881 }
1882 Stmts.pop_back();
1883 ObjCBcLabelNo.pop_back();
1884 return 0;
1885}
1886
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001887static void Write_RethrowObject(std::string &buf) {
1888 buf += "{ struct _FIN { _FIN(id reth) : rethrow(reth) {}\n";
1889 buf += "\t~_FIN() { if (rethrow) objc_exception_throw(rethrow); }\n";
1890 buf += "\tid rethrow;\n";
1891 buf += "\t} _fin_force_rethow(_rethrow);";
1892}
1893
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001894/// RewriteObjCSynchronizedStmt -
1895/// This routine rewrites @synchronized(expr) stmt;
1896/// into:
1897/// objc_sync_enter(expr);
1898/// @try stmt @finally { objc_sync_exit(expr); }
1899///
1900Stmt *RewriteModernObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
1901 // Get the start location and compute the semi location.
1902 SourceLocation startLoc = S->getLocStart();
1903 const char *startBuf = SM->getCharacterData(startLoc);
1904
1905 assert((*startBuf == '@') && "bogus @synchronized location");
1906
1907 std::string buf;
Fariborz Jahanian43f4f1e2012-11-07 00:43:05 +00001908 SourceLocation SynchLoc = S->getAtSynchronizedLoc();
1909 ConvertSourceLocationToLineDirective(SynchLoc, buf);
1910 buf += "{ id _rethrow = 0; id _sync_obj = ";
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001911
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001912 const char *lparenBuf = startBuf;
1913 while (*lparenBuf != '(') lparenBuf++;
1914 ReplaceText(startLoc, lparenBuf-startBuf+1, buf);
Fariborz Jahanian22e2f852012-03-17 17:46:02 +00001915
1916 buf = "; objc_sync_enter(_sync_obj);\n";
1917 buf += "try {\n\tstruct _SYNC_EXIT { _SYNC_EXIT(id arg) : sync_exit(arg) {}";
1918 buf += "\n\t~_SYNC_EXIT() {objc_sync_exit(sync_exit);}";
1919 buf += "\n\tid sync_exit;";
1920 buf += "\n\t} _sync_exit(_sync_obj);\n";
1921
1922 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1923 // the sync expression is typically a message expression that's already
1924 // been rewritten! (which implies the SourceLocation's are invalid).
1925 SourceLocation RParenExprLoc = S->getSynchBody()->getLocStart();
1926 const char *RParenExprLocBuf = SM->getCharacterData(RParenExprLoc);
1927 while (*RParenExprLocBuf != ')') RParenExprLocBuf--;
1928 RParenExprLoc = startLoc.getLocWithOffset(RParenExprLocBuf-startBuf);
1929
1930 SourceLocation LBranceLoc = S->getSynchBody()->getLocStart();
1931 const char *LBraceLocBuf = SM->getCharacterData(LBranceLoc);
1932 assert (*LBraceLocBuf == '{');
1933 ReplaceText(RParenExprLoc, (LBraceLocBuf - SM->getCharacterData(RParenExprLoc) + 1), buf);
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001934
Fariborz Jahanianb655bf02012-03-16 21:43:45 +00001935 SourceLocation startRBraceLoc = S->getSynchBody()->getLocEnd();
Matt Beaumont-Gay9ab511c2012-03-16 22:20:39 +00001936 assert((*SM->getCharacterData(startRBraceLoc) == '}') &&
1937 "bogus @synchronized block");
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001938
1939 buf = "} catch (id e) {_rethrow = e;}\n";
1940 Write_RethrowObject(buf);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001941 buf += "}\n";
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001942 buf += "}\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001943
Fariborz Jahanianb655bf02012-03-16 21:43:45 +00001944 ReplaceText(startRBraceLoc, 1, buf);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001945
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001946 return 0;
1947}
1948
1949void RewriteModernObjC::WarnAboutReturnGotoStmts(Stmt *S)
1950{
1951 // Perform a bottom up traversal of all children.
1952 for (Stmt::child_range CI = S->children(); CI; ++CI)
1953 if (*CI)
1954 WarnAboutReturnGotoStmts(*CI);
1955
1956 if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
1957 Diags.Report(Context->getFullLoc(S->getLocStart()),
1958 TryFinallyContainsReturnDiag);
1959 }
1960 return;
1961}
1962
Fariborz Jahanian042b91d2012-05-23 23:47:20 +00001963Stmt *RewriteModernObjC::RewriteObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S) {
1964 SourceLocation startLoc = S->getAtLoc();
1965 ReplaceText(startLoc, strlen("@autoreleasepool"), "/* @autoreleasepool */");
Fariborz Jahanianc9b72b62012-05-24 22:59:56 +00001966 ReplaceText(S->getSubStmt()->getLocStart(), 1,
1967 "{ __AtAutoreleasePool __autoreleasepool; ");
Fariborz Jahanian042b91d2012-05-23 23:47:20 +00001968
1969 return 0;
1970}
1971
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001972Stmt *RewriteModernObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001973 ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt();
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001974 bool noCatch = S->getNumCatchStmts() == 0;
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001975 std::string buf;
Fariborz Jahanianf616ae22012-11-06 23:25:49 +00001976 SourceLocation TryLocation = S->getAtTryLoc();
1977 ConvertSourceLocationToLineDirective(TryLocation, buf);
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001978
1979 if (finalStmt) {
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001980 if (noCatch)
Fariborz Jahanianf616ae22012-11-06 23:25:49 +00001981 buf += "{ id volatile _rethrow = 0;\n";
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001982 else {
Fariborz Jahanianf616ae22012-11-06 23:25:49 +00001983 buf += "{ id volatile _rethrow = 0;\ntry {\n";
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001984 }
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001985 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001986 // Get the start location and compute the semi location.
1987 SourceLocation startLoc = S->getLocStart();
1988 const char *startBuf = SM->getCharacterData(startLoc);
1989
1990 assert((*startBuf == '@') && "bogus @try location");
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001991 if (finalStmt)
1992 ReplaceText(startLoc, 1, buf);
1993 else
1994 // @try -> try
1995 ReplaceText(startLoc, 1, "");
1996
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001997 for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
1998 ObjCAtCatchStmt *Catch = S->getCatchStmt(I);
Fariborz Jahanian4c148812012-03-15 20:11:10 +00001999 VarDecl *catchDecl = Catch->getCatchParamDecl();
Fariborz Jahanianc38503b2012-03-12 23:58:28 +00002000
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002001 startLoc = Catch->getLocStart();
Fariborz Jahanian4c148812012-03-15 20:11:10 +00002002 bool AtRemoved = false;
2003 if (catchDecl) {
2004 QualType t = catchDecl->getType();
2005 if (const ObjCObjectPointerType *Ptr = t->getAs<ObjCObjectPointerType>()) {
2006 // Should be a pointer to a class.
2007 ObjCInterfaceDecl *IDecl = Ptr->getObjectType()->getInterface();
2008 if (IDecl) {
2009 std::string Result;
Fariborz Jahanianf616ae22012-11-06 23:25:49 +00002010 ConvertSourceLocationToLineDirective(Catch->getLocStart(), Result);
2011
Fariborz Jahanian4c148812012-03-15 20:11:10 +00002012 startBuf = SM->getCharacterData(startLoc);
2013 assert((*startBuf == '@') && "bogus @catch location");
2014 SourceLocation rParenLoc = Catch->getRParenLoc();
2015 const char *rParenBuf = SM->getCharacterData(rParenLoc);
2016
2017 // _objc_exc_Foo *_e as argument to catch.
Fariborz Jahanianf616ae22012-11-06 23:25:49 +00002018 Result += "catch (_objc_exc_"; Result += IDecl->getNameAsString();
Fariborz Jahanian4c148812012-03-15 20:11:10 +00002019 Result += " *_"; Result += catchDecl->getNameAsString();
2020 Result += ")";
2021 ReplaceText(startLoc, rParenBuf-startBuf+1, Result);
2022 // Foo *e = (Foo *)_e;
2023 Result.clear();
2024 Result = "{ ";
2025 Result += IDecl->getNameAsString();
2026 Result += " *"; Result += catchDecl->getNameAsString();
2027 Result += " = ("; Result += IDecl->getNameAsString(); Result += "*)";
2028 Result += "_"; Result += catchDecl->getNameAsString();
2029
2030 Result += "; ";
2031 SourceLocation lBraceLoc = Catch->getCatchBody()->getLocStart();
2032 ReplaceText(lBraceLoc, 1, Result);
2033 AtRemoved = true;
2034 }
2035 }
2036 }
2037 if (!AtRemoved)
2038 // @catch -> catch
2039 ReplaceText(startLoc, 1, "");
Fariborz Jahanianc38503b2012-03-12 23:58:28 +00002040
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002041 }
Fariborz Jahanian220419a2012-03-15 23:50:33 +00002042 if (finalStmt) {
2043 buf.clear();
Fariborz Jahanianf616ae22012-11-06 23:25:49 +00002044 SourceLocation FinallyLoc = finalStmt->getLocStart();
2045
2046 if (noCatch) {
2047 ConvertSourceLocationToLineDirective(FinallyLoc, buf);
2048 buf += "catch (id e) {_rethrow = e;}\n";
2049 }
2050 else {
2051 buf += "}\n";
2052 ConvertSourceLocationToLineDirective(FinallyLoc, buf);
2053 buf += "catch (id e) {_rethrow = e;}\n";
2054 }
2055
Fariborz Jahanian220419a2012-03-15 23:50:33 +00002056 SourceLocation startFinalLoc = finalStmt->getLocStart();
2057 ReplaceText(startFinalLoc, 8, buf);
2058 Stmt *body = finalStmt->getFinallyBody();
2059 SourceLocation startFinalBodyLoc = body->getLocStart();
2060 buf.clear();
Fariborz Jahanian542125f2012-03-16 21:33:16 +00002061 Write_RethrowObject(buf);
Fariborz Jahanian220419a2012-03-15 23:50:33 +00002062 ReplaceText(startFinalBodyLoc, 1, buf);
2063
2064 SourceLocation endFinalBodyLoc = body->getLocEnd();
2065 ReplaceText(endFinalBodyLoc, 1, "}\n}");
Fariborz Jahanian22e2f852012-03-17 17:46:02 +00002066 // Now check for any return/continue/go statements within the @try.
2067 WarnAboutReturnGotoStmts(S->getTryBody());
Fariborz Jahanian220419a2012-03-15 23:50:33 +00002068 }
2069
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002070 return 0;
2071}
2072
2073// This can't be done with ReplaceStmt(S, ThrowExpr), since
2074// the throw expression is typically a message expression that's already
2075// been rewritten! (which implies the SourceLocation's are invalid).
2076Stmt *RewriteModernObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
2077 // Get the start location and compute the semi location.
2078 SourceLocation startLoc = S->getLocStart();
2079 const char *startBuf = SM->getCharacterData(startLoc);
2080
2081 assert((*startBuf == '@') && "bogus @throw location");
2082
2083 std::string buf;
2084 /* void objc_exception_throw(id) __attribute__((noreturn)); */
2085 if (S->getThrowExpr())
2086 buf = "objc_exception_throw(";
Fariborz Jahanian40539462012-03-16 16:52:06 +00002087 else
2088 buf = "throw";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002089
2090 // handle "@ throw" correctly.
2091 const char *wBuf = strchr(startBuf, 'w');
2092 assert((*wBuf == 'w') && "@throw: can't find 'w'");
2093 ReplaceText(startLoc, wBuf-startBuf+1, buf);
2094
2095 const char *semiBuf = strchr(startBuf, ';');
2096 assert((*semiBuf == ';') && "@throw: can't find ';'");
2097 SourceLocation semiLoc = startLoc.getLocWithOffset(semiBuf-startBuf);
Fariborz Jahanian40539462012-03-16 16:52:06 +00002098 if (S->getThrowExpr())
2099 ReplaceText(semiLoc, 1, ");");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002100 return 0;
2101}
2102
2103Stmt *RewriteModernObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
2104 // Create a new string expression.
2105 QualType StrType = Context->getPointerType(Context->CharTy);
2106 std::string StrEncoding;
2107 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
2108 Expr *Replacement = StringLiteral::Create(*Context, StrEncoding,
2109 StringLiteral::Ascii, false,
2110 StrType, SourceLocation());
2111 ReplaceStmt(Exp, Replacement);
2112
2113 // Replace this subexpr in the parent.
2114 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2115 return Replacement;
2116}
2117
2118Stmt *RewriteModernObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
2119 if (!SelGetUidFunctionDecl)
2120 SynthSelGetUidFunctionDecl();
2121 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
2122 // Create a call to sel_registerName("selName").
2123 SmallVector<Expr*, 8> SelExprs;
2124 QualType argType = Context->getPointerType(Context->CharTy);
2125 SelExprs.push_back(StringLiteral::Create(*Context,
2126 Exp->getSelector().getAsString(),
2127 StringLiteral::Ascii, false,
2128 argType, SourceLocation()));
2129 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2130 &SelExprs[0], SelExprs.size());
2131 ReplaceStmt(Exp, SelExp);
2132 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2133 return SelExp;
2134}
2135
2136CallExpr *RewriteModernObjC::SynthesizeCallToFunctionDecl(
2137 FunctionDecl *FD, Expr **args, unsigned nargs, SourceLocation StartLoc,
2138 SourceLocation EndLoc) {
2139 // Get the type, we will need to reference it in a couple spots.
2140 QualType msgSendType = FD->getType();
2141
2142 // Create a reference to the objc_msgSend() declaration.
2143 DeclRefExpr *DRE =
John McCallf4b88a42012-03-10 09:33:50 +00002144 new (Context) DeclRefExpr(FD, false, msgSendType, VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002145
2146 // Now, we cast the reference to a pointer to the objc_msgSend type.
2147 QualType pToFunc = Context->getPointerType(msgSendType);
2148 ImplicitCastExpr *ICE =
2149 ImplicitCastExpr::Create(*Context, pToFunc, CK_FunctionToPointerDecay,
2150 DRE, 0, VK_RValue);
2151
2152 const FunctionType *FT = msgSendType->getAs<FunctionType>();
2153
2154 CallExpr *Exp =
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002155 new (Context) CallExpr(*Context, ICE, llvm::makeArrayRef(args, nargs),
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002156 FT->getCallResultType(*Context),
2157 VK_RValue, EndLoc);
2158 return Exp;
2159}
2160
2161static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
2162 const char *&startRef, const char *&endRef) {
2163 while (startBuf < endBuf) {
2164 if (*startBuf == '<')
2165 startRef = startBuf; // mark the start.
2166 if (*startBuf == '>') {
2167 if (startRef && *startRef == '<') {
2168 endRef = startBuf; // mark the end.
2169 return true;
2170 }
2171 return false;
2172 }
2173 startBuf++;
2174 }
2175 return false;
2176}
2177
2178static void scanToNextArgument(const char *&argRef) {
2179 int angle = 0;
2180 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
2181 if (*argRef == '<')
2182 angle++;
2183 else if (*argRef == '>')
2184 angle--;
2185 argRef++;
2186 }
2187 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
2188}
2189
2190bool RewriteModernObjC::needToScanForQualifiers(QualType T) {
2191 if (T->isObjCQualifiedIdType())
2192 return true;
2193 if (const PointerType *PT = T->getAs<PointerType>()) {
2194 if (PT->getPointeeType()->isObjCQualifiedIdType())
2195 return true;
2196 }
2197 if (T->isObjCObjectPointerType()) {
2198 T = T->getPointeeType();
2199 return T->isObjCQualifiedInterfaceType();
2200 }
2201 if (T->isArrayType()) {
2202 QualType ElemTy = Context->getBaseElementType(T);
2203 return needToScanForQualifiers(ElemTy);
2204 }
2205 return false;
2206}
2207
2208void RewriteModernObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
2209 QualType Type = E->getType();
2210 if (needToScanForQualifiers(Type)) {
2211 SourceLocation Loc, EndLoc;
2212
2213 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
2214 Loc = ECE->getLParenLoc();
2215 EndLoc = ECE->getRParenLoc();
2216 } else {
2217 Loc = E->getLocStart();
2218 EndLoc = E->getLocEnd();
2219 }
2220 // This will defend against trying to rewrite synthesized expressions.
2221 if (Loc.isInvalid() || EndLoc.isInvalid())
2222 return;
2223
2224 const char *startBuf = SM->getCharacterData(Loc);
2225 const char *endBuf = SM->getCharacterData(EndLoc);
2226 const char *startRef = 0, *endRef = 0;
2227 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2228 // Get the locations of the startRef, endRef.
2229 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-startBuf);
2230 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-startBuf+1);
2231 // Comment out the protocol references.
2232 InsertText(LessLoc, "/*");
2233 InsertText(GreaterLoc, "*/");
2234 }
2235 }
2236}
2237
2238void RewriteModernObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
2239 SourceLocation Loc;
2240 QualType Type;
2241 const FunctionProtoType *proto = 0;
2242 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
2243 Loc = VD->getLocation();
2244 Type = VD->getType();
2245 }
2246 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2247 Loc = FD->getLocation();
2248 // Check for ObjC 'id' and class types that have been adorned with protocol
2249 // information (id<p>, C<p>*). The protocol references need to be rewritten!
2250 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2251 assert(funcType && "missing function type");
2252 proto = dyn_cast<FunctionProtoType>(funcType);
2253 if (!proto)
2254 return;
2255 Type = proto->getResultType();
2256 }
2257 else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2258 Loc = FD->getLocation();
2259 Type = FD->getType();
2260 }
2261 else
2262 return;
2263
2264 if (needToScanForQualifiers(Type)) {
2265 // Since types are unique, we need to scan the buffer.
2266
2267 const char *endBuf = SM->getCharacterData(Loc);
2268 const char *startBuf = endBuf;
2269 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
2270 startBuf--; // scan backward (from the decl location) for return type.
2271 const char *startRef = 0, *endRef = 0;
2272 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2273 // Get the locations of the startRef, endRef.
2274 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-endBuf);
2275 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-endBuf+1);
2276 // Comment out the protocol references.
2277 InsertText(LessLoc, "/*");
2278 InsertText(GreaterLoc, "*/");
2279 }
2280 }
2281 if (!proto)
2282 return; // most likely, was a variable
2283 // Now check arguments.
2284 const char *startBuf = SM->getCharacterData(Loc);
2285 const char *startFuncBuf = startBuf;
2286 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
2287 if (needToScanForQualifiers(proto->getArgType(i))) {
2288 // Since types are unique, we need to scan the buffer.
2289
2290 const char *endBuf = startBuf;
2291 // scan forward (from the decl location) for argument types.
2292 scanToNextArgument(endBuf);
2293 const char *startRef = 0, *endRef = 0;
2294 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2295 // Get the locations of the startRef, endRef.
2296 SourceLocation LessLoc =
2297 Loc.getLocWithOffset(startRef-startFuncBuf);
2298 SourceLocation GreaterLoc =
2299 Loc.getLocWithOffset(endRef-startFuncBuf+1);
2300 // Comment out the protocol references.
2301 InsertText(LessLoc, "/*");
2302 InsertText(GreaterLoc, "*/");
2303 }
2304 startBuf = ++endBuf;
2305 }
2306 else {
2307 // If the function name is derived from a macro expansion, then the
2308 // argument buffer will not follow the name. Need to speak with Chris.
2309 while (*startBuf && *startBuf != ')' && *startBuf != ',')
2310 startBuf++; // scan forward (from the decl location) for argument types.
2311 startBuf++;
2312 }
2313 }
2314}
2315
2316void RewriteModernObjC::RewriteTypeOfDecl(VarDecl *ND) {
2317 QualType QT = ND->getType();
2318 const Type* TypePtr = QT->getAs<Type>();
2319 if (!isa<TypeOfExprType>(TypePtr))
2320 return;
2321 while (isa<TypeOfExprType>(TypePtr)) {
2322 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
2323 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
2324 TypePtr = QT->getAs<Type>();
2325 }
2326 // FIXME. This will not work for multiple declarators; as in:
2327 // __typeof__(a) b,c,d;
2328 std::string TypeAsString(QT.getAsString(Context->getPrintingPolicy()));
2329 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
2330 const char *startBuf = SM->getCharacterData(DeclLoc);
2331 if (ND->getInit()) {
2332 std::string Name(ND->getNameAsString());
2333 TypeAsString += " " + Name + " = ";
2334 Expr *E = ND->getInit();
2335 SourceLocation startLoc;
2336 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
2337 startLoc = ECE->getLParenLoc();
2338 else
2339 startLoc = E->getLocStart();
2340 startLoc = SM->getExpansionLoc(startLoc);
2341 const char *endBuf = SM->getCharacterData(startLoc);
2342 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2343 }
2344 else {
2345 SourceLocation X = ND->getLocEnd();
2346 X = SM->getExpansionLoc(X);
2347 const char *endBuf = SM->getCharacterData(X);
2348 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2349 }
2350}
2351
2352// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
2353void RewriteModernObjC::SynthSelGetUidFunctionDecl() {
2354 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
2355 SmallVector<QualType, 16> ArgTys;
2356 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2357 QualType getFuncType =
2358 getSimpleFunctionType(Context->getObjCSelType(), &ArgTys[0], ArgTys.size());
2359 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosiere3b29882013-01-04 22:40:33 +00002360 SourceLocation(),
2361 SourceLocation(),
2362 SelGetUidIdent, getFuncType, 0,
2363 SC_Extern, SC_None);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002364}
2365
2366void RewriteModernObjC::RewriteFunctionDecl(FunctionDecl *FD) {
2367 // declared in <objc/objc.h>
2368 if (FD->getIdentifier() &&
2369 FD->getName() == "sel_registerName") {
2370 SelGetUidFunctionDecl = FD;
2371 return;
2372 }
2373 RewriteObjCQualifiedInterfaceTypes(FD);
2374}
2375
2376void RewriteModernObjC::RewriteBlockPointerType(std::string& Str, QualType Type) {
2377 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
2378 const char *argPtr = TypeString.c_str();
2379 if (!strchr(argPtr, '^')) {
2380 Str += TypeString;
2381 return;
2382 }
2383 while (*argPtr) {
2384 Str += (*argPtr == '^' ? '*' : *argPtr);
2385 argPtr++;
2386 }
2387}
2388
2389// FIXME. Consolidate this routine with RewriteBlockPointerType.
2390void RewriteModernObjC::RewriteBlockPointerTypeVariable(std::string& Str,
2391 ValueDecl *VD) {
2392 QualType Type = VD->getType();
2393 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
2394 const char *argPtr = TypeString.c_str();
2395 int paren = 0;
2396 while (*argPtr) {
2397 switch (*argPtr) {
2398 case '(':
2399 Str += *argPtr;
2400 paren++;
2401 break;
2402 case ')':
2403 Str += *argPtr;
2404 paren--;
2405 break;
2406 case '^':
2407 Str += '*';
2408 if (paren == 1)
2409 Str += VD->getNameAsString();
2410 break;
2411 default:
2412 Str += *argPtr;
2413 break;
2414 }
2415 argPtr++;
2416 }
2417}
2418
Fariborz Jahanianb75f8de2012-04-19 00:50:01 +00002419void RewriteModernObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) {
2420 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
2421 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2422 const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(funcType);
2423 if (!proto)
2424 return;
2425 QualType Type = proto->getResultType();
2426 std::string FdStr = Type.getAsString(Context->getPrintingPolicy());
2427 FdStr += " ";
2428 FdStr += FD->getName();
2429 FdStr += "(";
2430 unsigned numArgs = proto->getNumArgs();
2431 for (unsigned i = 0; i < numArgs; i++) {
2432 QualType ArgType = proto->getArgType(i);
2433 RewriteBlockPointerType(FdStr, ArgType);
2434 if (i+1 < numArgs)
2435 FdStr += ", ";
2436 }
Fariborz Jahanianb5863da2012-04-19 16:30:28 +00002437 if (FD->isVariadic()) {
2438 FdStr += (numArgs > 0) ? ", ...);\n" : "...);\n";
2439 }
2440 else
2441 FdStr += ");\n";
Fariborz Jahanianb75f8de2012-04-19 00:50:01 +00002442 InsertText(FunLocStart, FdStr);
2443}
2444
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002445// SynthSuperContructorFunctionDecl - id __rw_objc_super(id obj, id super);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002446void RewriteModernObjC::SynthSuperContructorFunctionDecl() {
2447 if (SuperContructorFunctionDecl)
2448 return;
2449 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
2450 SmallVector<QualType, 16> ArgTys;
2451 QualType argT = Context->getObjCIdType();
2452 assert(!argT.isNull() && "Can't find 'id' type");
2453 ArgTys.push_back(argT);
2454 ArgTys.push_back(argT);
2455 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2456 &ArgTys[0], ArgTys.size());
2457 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosiere3b29882013-01-04 22:40:33 +00002458 SourceLocation(),
2459 SourceLocation(),
2460 msgSendIdent, msgSendType,
2461 0, SC_Extern, SC_None);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002462}
2463
2464// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
2465void RewriteModernObjC::SynthMsgSendFunctionDecl() {
2466 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
2467 SmallVector<QualType, 16> ArgTys;
2468 QualType argT = Context->getObjCIdType();
2469 assert(!argT.isNull() && "Can't find 'id' type");
2470 ArgTys.push_back(argT);
2471 argT = Context->getObjCSelType();
2472 assert(!argT.isNull() && "Can't find 'SEL' type");
2473 ArgTys.push_back(argT);
2474 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2475 &ArgTys[0], ArgTys.size(),
2476 true /*isVariadic*/);
2477 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosiere3b29882013-01-04 22:40:33 +00002478 SourceLocation(),
2479 SourceLocation(),
2480 msgSendIdent, msgSendType, 0,
2481 SC_Extern, SC_None);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002482}
2483
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002484// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(void);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002485void RewriteModernObjC::SynthMsgSendSuperFunctionDecl() {
2486 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002487 SmallVector<QualType, 2> ArgTys;
2488 ArgTys.push_back(Context->VoidTy);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002489 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002490 &ArgTys[0], 1,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002491 true /*isVariadic*/);
2492 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosiere3b29882013-01-04 22:40:33 +00002493 SourceLocation(),
2494 SourceLocation(),
2495 msgSendIdent, msgSendType, 0,
2496 SC_Extern, SC_None);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002497}
2498
2499// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
2500void RewriteModernObjC::SynthMsgSendStretFunctionDecl() {
2501 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
2502 SmallVector<QualType, 16> ArgTys;
2503 QualType argT = Context->getObjCIdType();
2504 assert(!argT.isNull() && "Can't find 'id' type");
2505 ArgTys.push_back(argT);
2506 argT = Context->getObjCSelType();
2507 assert(!argT.isNull() && "Can't find 'SEL' type");
2508 ArgTys.push_back(argT);
2509 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2510 &ArgTys[0], ArgTys.size(),
2511 true /*isVariadic*/);
2512 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosiere3b29882013-01-04 22:40:33 +00002513 SourceLocation(),
2514 SourceLocation(),
2515 msgSendIdent, msgSendType, 0,
2516 SC_Extern, SC_None);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002517}
2518
2519// SynthMsgSendSuperStretFunctionDecl -
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002520// id objc_msgSendSuper_stret(void);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002521void RewriteModernObjC::SynthMsgSendSuperStretFunctionDecl() {
2522 IdentifierInfo *msgSendIdent =
2523 &Context->Idents.get("objc_msgSendSuper_stret");
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002524 SmallVector<QualType, 2> ArgTys;
2525 ArgTys.push_back(Context->VoidTy);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002526 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002527 &ArgTys[0], 1,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002528 true /*isVariadic*/);
2529 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2530 SourceLocation(),
2531 SourceLocation(),
Chad Rosiere3b29882013-01-04 22:40:33 +00002532 msgSendIdent,
2533 msgSendType, 0,
2534 SC_Extern, SC_None);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002535}
2536
2537// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
2538void RewriteModernObjC::SynthMsgSendFpretFunctionDecl() {
2539 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2540 SmallVector<QualType, 16> ArgTys;
2541 QualType argT = Context->getObjCIdType();
2542 assert(!argT.isNull() && "Can't find 'id' type");
2543 ArgTys.push_back(argT);
2544 argT = Context->getObjCSelType();
2545 assert(!argT.isNull() && "Can't find 'SEL' type");
2546 ArgTys.push_back(argT);
2547 QualType msgSendType = getSimpleFunctionType(Context->DoubleTy,
2548 &ArgTys[0], ArgTys.size(),
2549 true /*isVariadic*/);
2550 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosiere3b29882013-01-04 22:40:33 +00002551 SourceLocation(),
2552 SourceLocation(),
2553 msgSendIdent, msgSendType, 0,
2554 SC_Extern, SC_None);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002555}
2556
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00002557// SynthGetClassFunctionDecl - Class objc_getClass(const char *name);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002558void RewriteModernObjC::SynthGetClassFunctionDecl() {
2559 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
2560 SmallVector<QualType, 16> ArgTys;
2561 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00002562 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002563 &ArgTys[0], ArgTys.size());
2564 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosiere3b29882013-01-04 22:40:33 +00002565 SourceLocation(),
2566 SourceLocation(),
2567 getClassIdent, getClassType, 0,
2568 SC_Extern, SC_None);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002569}
2570
2571// SynthGetSuperClassFunctionDecl - Class class_getSuperclass(Class cls);
2572void RewriteModernObjC::SynthGetSuperClassFunctionDecl() {
2573 IdentifierInfo *getSuperClassIdent =
2574 &Context->Idents.get("class_getSuperclass");
2575 SmallVector<QualType, 16> ArgTys;
2576 ArgTys.push_back(Context->getObjCClassType());
2577 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
2578 &ArgTys[0], ArgTys.size());
2579 GetSuperClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2580 SourceLocation(),
2581 SourceLocation(),
2582 getSuperClassIdent,
2583 getClassType, 0,
Chad Rosiere3b29882013-01-04 22:40:33 +00002584 SC_Extern, SC_None);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002585}
2586
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00002587// SynthGetMetaClassFunctionDecl - Class objc_getMetaClass(const char *name);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002588void RewriteModernObjC::SynthGetMetaClassFunctionDecl() {
2589 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2590 SmallVector<QualType, 16> ArgTys;
2591 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00002592 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002593 &ArgTys[0], ArgTys.size());
2594 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosiere3b29882013-01-04 22:40:33 +00002595 SourceLocation(),
2596 SourceLocation(),
2597 getClassIdent, getClassType,
2598 0, SC_Extern, SC_None);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002599}
2600
2601Stmt *RewriteModernObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
2602 QualType strType = getConstantStringStructType();
2603
2604 std::string S = "__NSConstantStringImpl_";
2605
2606 std::string tmpName = InFileName;
2607 unsigned i;
2608 for (i=0; i < tmpName.length(); i++) {
2609 char c = tmpName.at(i);
2610 // replace any non alphanumeric characters with '_'.
2611 if (!isalpha(c) && (c < '0' || c > '9'))
2612 tmpName[i] = '_';
2613 }
2614 S += tmpName;
2615 S += "_";
2616 S += utostr(NumObjCStringLiterals++);
2617
2618 Preamble += "static __NSConstantStringImpl " + S;
2619 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2620 Preamble += "0x000007c8,"; // utf8_str
2621 // The pretty printer for StringLiteral handles escape characters properly.
2622 std::string prettyBufS;
2623 llvm::raw_string_ostream prettyBuf(prettyBufS);
Richard Smithd1420c62012-08-16 03:56:14 +00002624 Exp->getString()->printPretty(prettyBuf, 0, PrintingPolicy(LangOpts));
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002625 Preamble += prettyBuf.str();
2626 Preamble += ",";
2627 Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
2628
2629 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
2630 SourceLocation(), &Context->Idents.get(S),
2631 strType, 0, SC_Static, SC_None);
John McCallf4b88a42012-03-10 09:33:50 +00002632 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, false, strType, VK_LValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002633 SourceLocation());
2634 Expr *Unop = new (Context) UnaryOperator(DRE, UO_AddrOf,
2635 Context->getPointerType(DRE->getType()),
2636 VK_RValue, OK_Ordinary,
2637 SourceLocation());
2638 // cast to NSConstantString *
2639 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(),
2640 CK_CPointerToObjCPointerCast, Unop);
2641 ReplaceStmt(Exp, cast);
2642 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2643 return cast;
2644}
2645
Fariborz Jahanian55947042012-03-27 20:17:30 +00002646Stmt *RewriteModernObjC::RewriteObjCBoolLiteralExpr(ObjCBoolLiteralExpr *Exp) {
2647 unsigned IntSize =
2648 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
2649
2650 Expr *FlagExp = IntegerLiteral::Create(*Context,
2651 llvm::APInt(IntSize, Exp->getValue()),
2652 Context->IntTy, Exp->getLocation());
2653 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Context->ObjCBuiltinBoolTy,
2654 CK_BitCast, FlagExp);
2655 ParenExpr *PE = new (Context) ParenExpr(Exp->getLocation(), Exp->getExprLoc(),
2656 cast);
2657 ReplaceStmt(Exp, PE);
2658 return PE;
2659}
2660
Patrick Beardeb382ec2012-04-19 00:25:12 +00002661Stmt *RewriteModernObjC::RewriteObjCBoxedExpr(ObjCBoxedExpr *Exp) {
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002662 // synthesize declaration of helper functions needed in this routine.
2663 if (!SelGetUidFunctionDecl)
2664 SynthSelGetUidFunctionDecl();
2665 // use objc_msgSend() for all.
2666 if (!MsgSendFunctionDecl)
2667 SynthMsgSendFunctionDecl();
2668 if (!GetClassFunctionDecl)
2669 SynthGetClassFunctionDecl();
2670
2671 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2672 SourceLocation StartLoc = Exp->getLocStart();
2673 SourceLocation EndLoc = Exp->getLocEnd();
2674
2675 // Synthesize a call to objc_msgSend().
2676 SmallVector<Expr*, 4> MsgExprs;
2677 SmallVector<Expr*, 4> ClsExprs;
2678 QualType argType = Context->getPointerType(Context->CharTy);
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002679
Patrick Beardeb382ec2012-04-19 00:25:12 +00002680 // Create a call to objc_getClass("<BoxingClass>"). It will be the 1st argument.
2681 ObjCMethodDecl *BoxingMethod = Exp->getBoxingMethod();
2682 ObjCInterfaceDecl *BoxingClass = BoxingMethod->getClassInterface();
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002683
Patrick Beardeb382ec2012-04-19 00:25:12 +00002684 IdentifierInfo *clsName = BoxingClass->getIdentifier();
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002685 ClsExprs.push_back(StringLiteral::Create(*Context,
2686 clsName->getName(),
2687 StringLiteral::Ascii, false,
2688 argType, SourceLocation()));
2689 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2690 &ClsExprs[0],
2691 ClsExprs.size(),
2692 StartLoc, EndLoc);
2693 MsgExprs.push_back(Cls);
2694
Patrick Beardeb382ec2012-04-19 00:25:12 +00002695 // Create a call to sel_registerName("<BoxingMethod>:"), etc.
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002696 // it will be the 2nd argument.
2697 SmallVector<Expr*, 4> SelExprs;
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002698 SelExprs.push_back(StringLiteral::Create(*Context,
Patrick Beardeb382ec2012-04-19 00:25:12 +00002699 BoxingMethod->getSelector().getAsString(),
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002700 StringLiteral::Ascii, false,
2701 argType, SourceLocation()));
2702 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2703 &SelExprs[0], SelExprs.size(),
2704 StartLoc, EndLoc);
2705 MsgExprs.push_back(SelExp);
2706
Patrick Beardeb382ec2012-04-19 00:25:12 +00002707 // User provided sub-expression is the 3rd, and last, argument.
2708 Expr *subExpr = Exp->getSubExpr();
2709 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(subExpr)) {
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002710 QualType type = ICE->getType();
2711 const Expr *SubExpr = ICE->IgnoreParenImpCasts();
2712 CastKind CK = CK_BitCast;
2713 if (SubExpr->getType()->isIntegralType(*Context) && type->isBooleanType())
2714 CK = CK_IntegralToBoolean;
Patrick Beardeb382ec2012-04-19 00:25:12 +00002715 subExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, subExpr);
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002716 }
Patrick Beardeb382ec2012-04-19 00:25:12 +00002717 MsgExprs.push_back(subExpr);
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002718
2719 SmallVector<QualType, 4> ArgTypes;
2720 ArgTypes.push_back(Context->getObjCIdType());
2721 ArgTypes.push_back(Context->getObjCSelType());
Patrick Beardeb382ec2012-04-19 00:25:12 +00002722 for (ObjCMethodDecl::param_iterator PI = BoxingMethod->param_begin(),
2723 E = BoxingMethod->param_end(); PI != E; ++PI)
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002724 ArgTypes.push_back((*PI)->getType());
Patrick Beardeb382ec2012-04-19 00:25:12 +00002725
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002726 QualType returnType = Exp->getType();
2727 // Get the type, we will need to reference it in a couple spots.
2728 QualType msgSendType = MsgSendFlavor->getType();
2729
2730 // Create a reference to the objc_msgSend() declaration.
2731 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
2732 VK_LValue, SourceLocation());
2733
2734 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
Patrick Beardeb382ec2012-04-19 00:25:12 +00002735 Context->getPointerType(Context->VoidTy),
2736 CK_BitCast, DRE);
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002737
2738 // Now do the "normal" pointer to function cast.
2739 QualType castType =
Patrick Beardeb382ec2012-04-19 00:25:12 +00002740 getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
2741 BoxingMethod->isVariadic());
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002742 castType = Context->getPointerType(castType);
2743 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2744 cast);
2745
2746 // Don't forget the parens to enforce the proper binding.
2747 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
2748
2749 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002750 CallExpr *CE = new (Context) CallExpr(*Context, PE, MsgExprs,
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002751 FT->getResultType(), VK_RValue,
2752 EndLoc);
2753 ReplaceStmt(Exp, CE);
2754 return CE;
2755}
2756
Fariborz Jahanian86cff602012-03-30 23:35:47 +00002757Stmt *RewriteModernObjC::RewriteObjCArrayLiteralExpr(ObjCArrayLiteral *Exp) {
2758 // synthesize declaration of helper functions needed in this routine.
2759 if (!SelGetUidFunctionDecl)
2760 SynthSelGetUidFunctionDecl();
2761 // use objc_msgSend() for all.
2762 if (!MsgSendFunctionDecl)
2763 SynthMsgSendFunctionDecl();
2764 if (!GetClassFunctionDecl)
2765 SynthGetClassFunctionDecl();
2766
2767 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2768 SourceLocation StartLoc = Exp->getLocStart();
2769 SourceLocation EndLoc = Exp->getLocEnd();
2770
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00002771 // Build the expression: __NSContainer_literal(int, ...).arr
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00002772 QualType IntQT = Context->IntTy;
2773 QualType NSArrayFType =
2774 getSimpleFunctionType(Context->VoidTy, &IntQT, 1, true);
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00002775 std::string NSArrayFName("__NSContainer_literal");
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00002776 FunctionDecl *NSArrayFD = SynthBlockInitFunctionDecl(NSArrayFName);
2777 DeclRefExpr *NSArrayDRE =
2778 new (Context) DeclRefExpr(NSArrayFD, false, NSArrayFType, VK_RValue,
2779 SourceLocation());
2780
2781 SmallVector<Expr*, 16> InitExprs;
2782 unsigned NumElements = Exp->getNumElements();
2783 unsigned UnsignedIntSize =
2784 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
2785 Expr *count = IntegerLiteral::Create(*Context,
2786 llvm::APInt(UnsignedIntSize, NumElements),
2787 Context->UnsignedIntTy, SourceLocation());
2788 InitExprs.push_back(count);
2789 for (unsigned i = 0; i < NumElements; i++)
2790 InitExprs.push_back(Exp->getElement(i));
2791 Expr *NSArrayCallExpr =
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002792 new (Context) CallExpr(*Context, NSArrayDRE, InitExprs,
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00002793 NSArrayFType, VK_LValue, SourceLocation());
2794
2795 FieldDecl *ARRFD = FieldDecl::Create(*Context, 0, SourceLocation(),
2796 SourceLocation(),
2797 &Context->Idents.get("arr"),
2798 Context->getPointerType(Context->VoidPtrTy), 0,
2799 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smithca523302012-06-10 03:12:00 +00002800 ICIS_NoInit);
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00002801 MemberExpr *ArrayLiteralME =
2802 new (Context) MemberExpr(NSArrayCallExpr, false, ARRFD,
2803 SourceLocation(),
2804 ARRFD->getType(), VK_LValue,
2805 OK_Ordinary);
2806 QualType ConstIdT = Context->getObjCIdType().withConst();
2807 CStyleCastExpr * ArrayLiteralObjects =
2808 NoTypeInfoCStyleCastExpr(Context,
2809 Context->getPointerType(ConstIdT),
2810 CK_BitCast,
2811 ArrayLiteralME);
2812
Fariborz Jahanian86cff602012-03-30 23:35:47 +00002813 // Synthesize a call to objc_msgSend().
2814 SmallVector<Expr*, 32> MsgExprs;
2815 SmallVector<Expr*, 4> ClsExprs;
2816 QualType argType = Context->getPointerType(Context->CharTy);
2817 QualType expType = Exp->getType();
2818
2819 // Create a call to objc_getClass("NSArray"). It will be th 1st argument.
2820 ObjCInterfaceDecl *Class =
2821 expType->getPointeeType()->getAs<ObjCObjectType>()->getInterface();
2822
2823 IdentifierInfo *clsName = Class->getIdentifier();
2824 ClsExprs.push_back(StringLiteral::Create(*Context,
2825 clsName->getName(),
2826 StringLiteral::Ascii, false,
2827 argType, SourceLocation()));
2828 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2829 &ClsExprs[0],
2830 ClsExprs.size(),
2831 StartLoc, EndLoc);
2832 MsgExprs.push_back(Cls);
2833
2834 // Create a call to sel_registerName("arrayWithObjects:count:").
2835 // it will be the 2nd argument.
2836 SmallVector<Expr*, 4> SelExprs;
2837 ObjCMethodDecl *ArrayMethod = Exp->getArrayWithObjectsMethod();
2838 SelExprs.push_back(StringLiteral::Create(*Context,
2839 ArrayMethod->getSelector().getAsString(),
2840 StringLiteral::Ascii, false,
2841 argType, SourceLocation()));
2842 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2843 &SelExprs[0], SelExprs.size(),
2844 StartLoc, EndLoc);
2845 MsgExprs.push_back(SelExp);
2846
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00002847 // (const id [])objects
2848 MsgExprs.push_back(ArrayLiteralObjects);
Fariborz Jahanian86cff602012-03-30 23:35:47 +00002849
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00002850 // (NSUInteger)cnt
2851 Expr *cnt = IntegerLiteral::Create(*Context,
2852 llvm::APInt(UnsignedIntSize, NumElements),
2853 Context->UnsignedIntTy, SourceLocation());
2854 MsgExprs.push_back(cnt);
Fariborz Jahanian86cff602012-03-30 23:35:47 +00002855
2856
2857 SmallVector<QualType, 4> ArgTypes;
2858 ArgTypes.push_back(Context->getObjCIdType());
2859 ArgTypes.push_back(Context->getObjCSelType());
2860 for (ObjCMethodDecl::param_iterator PI = ArrayMethod->param_begin(),
2861 E = ArrayMethod->param_end(); PI != E; ++PI)
2862 ArgTypes.push_back((*PI)->getType());
2863
2864 QualType returnType = Exp->getType();
2865 // Get the type, we will need to reference it in a couple spots.
2866 QualType msgSendType = MsgSendFlavor->getType();
2867
2868 // Create a reference to the objc_msgSend() declaration.
2869 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
2870 VK_LValue, SourceLocation());
2871
2872 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
2873 Context->getPointerType(Context->VoidTy),
2874 CK_BitCast, DRE);
2875
2876 // Now do the "normal" pointer to function cast.
2877 QualType castType =
2878 getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
2879 ArrayMethod->isVariadic());
2880 castType = Context->getPointerType(castType);
2881 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2882 cast);
2883
2884 // Don't forget the parens to enforce the proper binding.
2885 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
2886
2887 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002888 CallExpr *CE = new (Context) CallExpr(*Context, PE, MsgExprs,
Fariborz Jahanian86cff602012-03-30 23:35:47 +00002889 FT->getResultType(), VK_RValue,
2890 EndLoc);
2891 ReplaceStmt(Exp, CE);
2892 return CE;
2893}
2894
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00002895Stmt *RewriteModernObjC::RewriteObjCDictionaryLiteralExpr(ObjCDictionaryLiteral *Exp) {
2896 // synthesize declaration of helper functions needed in this routine.
2897 if (!SelGetUidFunctionDecl)
2898 SynthSelGetUidFunctionDecl();
2899 // use objc_msgSend() for all.
2900 if (!MsgSendFunctionDecl)
2901 SynthMsgSendFunctionDecl();
2902 if (!GetClassFunctionDecl)
2903 SynthGetClassFunctionDecl();
2904
2905 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2906 SourceLocation StartLoc = Exp->getLocStart();
2907 SourceLocation EndLoc = Exp->getLocEnd();
2908
2909 // Build the expression: __NSContainer_literal(int, ...).arr
2910 QualType IntQT = Context->IntTy;
2911 QualType NSDictFType =
2912 getSimpleFunctionType(Context->VoidTy, &IntQT, 1, true);
2913 std::string NSDictFName("__NSContainer_literal");
2914 FunctionDecl *NSDictFD = SynthBlockInitFunctionDecl(NSDictFName);
2915 DeclRefExpr *NSDictDRE =
2916 new (Context) DeclRefExpr(NSDictFD, false, NSDictFType, VK_RValue,
2917 SourceLocation());
2918
2919 SmallVector<Expr*, 16> KeyExprs;
2920 SmallVector<Expr*, 16> ValueExprs;
2921
2922 unsigned NumElements = Exp->getNumElements();
2923 unsigned UnsignedIntSize =
2924 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
2925 Expr *count = IntegerLiteral::Create(*Context,
2926 llvm::APInt(UnsignedIntSize, NumElements),
2927 Context->UnsignedIntTy, SourceLocation());
2928 KeyExprs.push_back(count);
2929 ValueExprs.push_back(count);
2930 for (unsigned i = 0; i < NumElements; i++) {
2931 ObjCDictionaryElement Element = Exp->getKeyValueElement(i);
2932 KeyExprs.push_back(Element.Key);
2933 ValueExprs.push_back(Element.Value);
2934 }
2935
2936 // (const id [])objects
2937 Expr *NSValueCallExpr =
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002938 new (Context) CallExpr(*Context, NSDictDRE, ValueExprs,
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00002939 NSDictFType, VK_LValue, SourceLocation());
2940
2941 FieldDecl *ARRFD = FieldDecl::Create(*Context, 0, SourceLocation(),
2942 SourceLocation(),
2943 &Context->Idents.get("arr"),
2944 Context->getPointerType(Context->VoidPtrTy), 0,
2945 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smithca523302012-06-10 03:12:00 +00002946 ICIS_NoInit);
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00002947 MemberExpr *DictLiteralValueME =
2948 new (Context) MemberExpr(NSValueCallExpr, false, ARRFD,
2949 SourceLocation(),
2950 ARRFD->getType(), VK_LValue,
2951 OK_Ordinary);
2952 QualType ConstIdT = Context->getObjCIdType().withConst();
2953 CStyleCastExpr * DictValueObjects =
2954 NoTypeInfoCStyleCastExpr(Context,
2955 Context->getPointerType(ConstIdT),
2956 CK_BitCast,
2957 DictLiteralValueME);
2958 // (const id <NSCopying> [])keys
2959 Expr *NSKeyCallExpr =
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002960 new (Context) CallExpr(*Context, NSDictDRE, KeyExprs,
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00002961 NSDictFType, VK_LValue, SourceLocation());
2962
2963 MemberExpr *DictLiteralKeyME =
2964 new (Context) MemberExpr(NSKeyCallExpr, false, ARRFD,
2965 SourceLocation(),
2966 ARRFD->getType(), VK_LValue,
2967 OK_Ordinary);
2968
2969 CStyleCastExpr * DictKeyObjects =
2970 NoTypeInfoCStyleCastExpr(Context,
2971 Context->getPointerType(ConstIdT),
2972 CK_BitCast,
2973 DictLiteralKeyME);
2974
2975
2976
2977 // Synthesize a call to objc_msgSend().
2978 SmallVector<Expr*, 32> MsgExprs;
2979 SmallVector<Expr*, 4> ClsExprs;
2980 QualType argType = Context->getPointerType(Context->CharTy);
2981 QualType expType = Exp->getType();
2982
2983 // Create a call to objc_getClass("NSArray"). It will be th 1st argument.
2984 ObjCInterfaceDecl *Class =
2985 expType->getPointeeType()->getAs<ObjCObjectType>()->getInterface();
2986
2987 IdentifierInfo *clsName = Class->getIdentifier();
2988 ClsExprs.push_back(StringLiteral::Create(*Context,
2989 clsName->getName(),
2990 StringLiteral::Ascii, false,
2991 argType, SourceLocation()));
2992 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2993 &ClsExprs[0],
2994 ClsExprs.size(),
2995 StartLoc, EndLoc);
2996 MsgExprs.push_back(Cls);
2997
2998 // Create a call to sel_registerName("arrayWithObjects:count:").
2999 // it will be the 2nd argument.
3000 SmallVector<Expr*, 4> SelExprs;
3001 ObjCMethodDecl *DictMethod = Exp->getDictWithObjectsMethod();
3002 SelExprs.push_back(StringLiteral::Create(*Context,
3003 DictMethod->getSelector().getAsString(),
3004 StringLiteral::Ascii, false,
3005 argType, SourceLocation()));
3006 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
3007 &SelExprs[0], SelExprs.size(),
3008 StartLoc, EndLoc);
3009 MsgExprs.push_back(SelExp);
3010
3011 // (const id [])objects
3012 MsgExprs.push_back(DictValueObjects);
3013
3014 // (const id <NSCopying> [])keys
3015 MsgExprs.push_back(DictKeyObjects);
3016
3017 // (NSUInteger)cnt
3018 Expr *cnt = IntegerLiteral::Create(*Context,
3019 llvm::APInt(UnsignedIntSize, NumElements),
3020 Context->UnsignedIntTy, SourceLocation());
3021 MsgExprs.push_back(cnt);
3022
3023
3024 SmallVector<QualType, 8> ArgTypes;
3025 ArgTypes.push_back(Context->getObjCIdType());
3026 ArgTypes.push_back(Context->getObjCSelType());
3027 for (ObjCMethodDecl::param_iterator PI = DictMethod->param_begin(),
3028 E = DictMethod->param_end(); PI != E; ++PI) {
3029 QualType T = (*PI)->getType();
3030 if (const PointerType* PT = T->getAs<PointerType>()) {
3031 QualType PointeeTy = PT->getPointeeType();
3032 convertToUnqualifiedObjCType(PointeeTy);
3033 T = Context->getPointerType(PointeeTy);
3034 }
3035 ArgTypes.push_back(T);
3036 }
3037
3038 QualType returnType = Exp->getType();
3039 // Get the type, we will need to reference it in a couple spots.
3040 QualType msgSendType = MsgSendFlavor->getType();
3041
3042 // Create a reference to the objc_msgSend() declaration.
3043 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
3044 VK_LValue, SourceLocation());
3045
3046 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
3047 Context->getPointerType(Context->VoidTy),
3048 CK_BitCast, DRE);
3049
3050 // Now do the "normal" pointer to function cast.
3051 QualType castType =
3052 getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
3053 DictMethod->isVariadic());
3054 castType = Context->getPointerType(castType);
3055 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
3056 cast);
3057
3058 // Don't forget the parens to enforce the proper binding.
3059 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
3060
3061 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003062 CallExpr *CE = new (Context) CallExpr(*Context, PE, MsgExprs,
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00003063 FT->getResultType(), VK_RValue,
3064 EndLoc);
3065 ReplaceStmt(Exp, CE);
3066 return CE;
3067}
3068
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003069// struct __rw_objc_super {
3070// struct objc_object *object; struct objc_object *superClass;
3071// };
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003072QualType RewriteModernObjC::getSuperStructType() {
3073 if (!SuperStructDecl) {
3074 SuperStructDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
3075 SourceLocation(), SourceLocation(),
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003076 &Context->Idents.get("__rw_objc_super"));
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003077 QualType FieldTypes[2];
3078
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003079 // struct objc_object *object;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003080 FieldTypes[0] = Context->getObjCIdType();
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003081 // struct objc_object *superClass;
3082 FieldTypes[1] = Context->getObjCIdType();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003083
3084 // Create fields
3085 for (unsigned i = 0; i < 2; ++i) {
3086 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
3087 SourceLocation(),
3088 SourceLocation(), 0,
3089 FieldTypes[i], 0,
3090 /*BitWidth=*/0,
3091 /*Mutable=*/false,
Richard Smithca523302012-06-10 03:12:00 +00003092 ICIS_NoInit));
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003093 }
3094
3095 SuperStructDecl->completeDefinition();
3096 }
3097 return Context->getTagDeclType(SuperStructDecl);
3098}
3099
3100QualType RewriteModernObjC::getConstantStringStructType() {
3101 if (!ConstantStringDecl) {
3102 ConstantStringDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
3103 SourceLocation(), SourceLocation(),
3104 &Context->Idents.get("__NSConstantStringImpl"));
3105 QualType FieldTypes[4];
3106
3107 // struct objc_object *receiver;
3108 FieldTypes[0] = Context->getObjCIdType();
3109 // int flags;
3110 FieldTypes[1] = Context->IntTy;
3111 // char *str;
3112 FieldTypes[2] = Context->getPointerType(Context->CharTy);
3113 // long length;
3114 FieldTypes[3] = Context->LongTy;
3115
3116 // Create fields
3117 for (unsigned i = 0; i < 4; ++i) {
3118 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
3119 ConstantStringDecl,
3120 SourceLocation(),
3121 SourceLocation(), 0,
3122 FieldTypes[i], 0,
3123 /*BitWidth=*/0,
3124 /*Mutable=*/true,
Richard Smithca523302012-06-10 03:12:00 +00003125 ICIS_NoInit));
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003126 }
3127
3128 ConstantStringDecl->completeDefinition();
3129 }
3130 return Context->getTagDeclType(ConstantStringDecl);
3131}
3132
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +00003133/// getFunctionSourceLocation - returns start location of a function
3134/// definition. Complication arises when function has declared as
3135/// extern "C" or extern "C" {...}
3136static SourceLocation getFunctionSourceLocation (RewriteModernObjC &R,
3137 FunctionDecl *FD) {
3138 if (FD->isExternC() && !FD->isMain()) {
3139 const DeclContext *DC = FD->getDeclContext();
3140 if (const LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(DC))
3141 // if it is extern "C" {...}, return function decl's own location.
3142 if (!LSD->getRBraceLoc().isValid())
3143 return LSD->getExternLoc();
3144 }
3145 if (FD->getStorageClassAsWritten() != SC_None)
3146 R.RewriteBlockLiteralFunctionDecl(FD);
3147 return FD->getTypeSpecStartLoc();
3148}
3149
Fariborz Jahanian96205962012-11-06 17:30:23 +00003150void RewriteModernObjC::RewriteLineDirective(const Decl *D) {
3151
3152 SourceLocation Location = D->getLocation();
3153
Fariborz Jahanianada71912013-02-08 00:27:34 +00003154 if (Location.isFileID() && GenerateLineInfo) {
Fariborz Jahanian3b45ca92012-11-07 18:15:53 +00003155 std::string LineString("\n#line ");
Fariborz Jahanian96205962012-11-06 17:30:23 +00003156 PresumedLoc PLoc = SM->getPresumedLoc(Location);
3157 LineString += utostr(PLoc.getLine());
3158 LineString += " \"";
NAKAMURA Takumiba529a92012-11-06 22:45:31 +00003159 LineString += Lexer::Stringify(PLoc.getFilename());
Fariborz Jahanian96205962012-11-06 17:30:23 +00003160 if (isa<ObjCMethodDecl>(D))
3161 LineString += "\"";
3162 else LineString += "\"\n";
3163
3164 Location = D->getLocStart();
3165 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
3166 if (FD->isExternC() && !FD->isMain()) {
3167 const DeclContext *DC = FD->getDeclContext();
3168 if (const LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(DC))
3169 // if it is extern "C" {...}, return function decl's own location.
3170 if (!LSD->getRBraceLoc().isValid())
3171 Location = LSD->getExternLoc();
3172 }
3173 }
3174 InsertText(Location, LineString);
3175 }
3176}
3177
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +00003178/// SynthMsgSendStretCallExpr - This routine translates message expression
3179/// into a call to objc_msgSend_stret() entry point. Tricky part is that
3180/// nil check on receiver must be performed before calling objc_msgSend_stret.
3181/// MsgSendStretFlavor - function declaration objc_msgSend_stret(...)
3182/// msgSendType - function type of objc_msgSend_stret(...)
3183/// returnType - Result type of the method being synthesized.
3184/// ArgTypes - type of the arguments passed to objc_msgSend_stret, starting with receiver type.
3185/// MsgExprs - list of argument expressions being passed to objc_msgSend_stret,
3186/// starting with receiver.
3187/// Method - Method being rewritten.
3188Expr *RewriteModernObjC::SynthMsgSendStretCallExpr(FunctionDecl *MsgSendStretFlavor,
3189 QualType msgSendType,
3190 QualType returnType,
3191 SmallVectorImpl<QualType> &ArgTypes,
3192 SmallVectorImpl<Expr*> &MsgExprs,
3193 ObjCMethodDecl *Method) {
3194 // Now do the "normal" pointer to function cast.
3195 QualType castType = getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
3196 Method ? Method->isVariadic() : false);
3197 castType = Context->getPointerType(castType);
3198
3199 // build type for containing the objc_msgSend_stret object.
3200 static unsigned stretCount=0;
3201 std::string name = "__Stret"; name += utostr(stretCount);
Fariborz Jahanian2ca5af22012-07-25 21:48:36 +00003202 std::string str =
3203 "extern \"C\" void * __cdecl memset(void *_Dst, int _Val, size_t _Size);\n";
3204 str += "struct "; str += name;
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +00003205 str += " {\n\t";
3206 str += name;
3207 str += "(id receiver, SEL sel";
3208 for (unsigned i = 2; i < ArgTypes.size(); i++) {
Fariborz Jahanian6734ec42012-06-29 19:55:46 +00003209 std::string ArgName = "arg"; ArgName += utostr(i);
3210 ArgTypes[i].getAsStringInternal(ArgName, Context->getPrintingPolicy());
3211 str += ", "; str += ArgName;
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +00003212 }
3213 // could be vararg.
3214 for (unsigned i = ArgTypes.size(); i < MsgExprs.size(); i++) {
Fariborz Jahanian6734ec42012-06-29 19:55:46 +00003215 std::string ArgName = "arg"; ArgName += utostr(i);
3216 MsgExprs[i]->getType().getAsStringInternal(ArgName,
3217 Context->getPrintingPolicy());
3218 str += ", "; str += ArgName;
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +00003219 }
3220
3221 str += ") {\n";
3222 str += "\t if (receiver == 0)\n";
3223 str += "\t memset((void*)&s, 0, sizeof(s));\n";
3224 str += "\t else\n";
3225 str += "\t s = (("; str += castType.getAsString(Context->getPrintingPolicy());
3226 str += ")(void *)objc_msgSend_stret)(receiver, sel";
3227 for (unsigned i = 2; i < ArgTypes.size(); i++) {
3228 str += ", arg"; str += utostr(i);
3229 }
3230 // could be vararg.
3231 for (unsigned i = ArgTypes.size(); i < MsgExprs.size(); i++) {
3232 str += ", arg"; str += utostr(i);
3233 }
3234
3235 str += ");\n";
3236 str += "\t}\n";
3237 str += "\t"; str += returnType.getAsString(Context->getPrintingPolicy());
3238 str += " s;\n";
3239 str += "};\n\n";
Fariborz Jahaniana6e5a6e2012-08-21 18:56:50 +00003240 SourceLocation FunLocStart;
3241 if (CurFunctionDef)
3242 FunLocStart = getFunctionSourceLocation(*this, CurFunctionDef);
3243 else {
3244 assert(CurMethodDef && "SynthMsgSendStretCallExpr - CurMethodDef is null");
3245 FunLocStart = CurMethodDef->getLocStart();
3246 }
3247
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +00003248 InsertText(FunLocStart, str);
3249 ++stretCount;
3250
3251 // AST for __Stretn(receiver, args).s;
3252 IdentifierInfo *ID = &Context->Idents.get(name);
3253 FunctionDecl *FD = FunctionDecl::Create(*Context, TUDecl, SourceLocation(),
Chad Rosiere3b29882013-01-04 22:40:33 +00003254 SourceLocation(), ID, castType, 0,
3255 SC_Extern, SC_None, false, false);
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +00003256 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, false, castType, VK_RValue,
3257 SourceLocation());
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003258 CallExpr *STCE = new (Context) CallExpr(*Context, DRE, MsgExprs,
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +00003259 castType, VK_LValue, SourceLocation());
3260
3261 FieldDecl *FieldD = FieldDecl::Create(*Context, 0, SourceLocation(),
3262 SourceLocation(),
3263 &Context->Idents.get("s"),
3264 returnType, 0,
3265 /*BitWidth=*/0, /*Mutable=*/true,
3266 ICIS_NoInit);
3267 MemberExpr *ME = new (Context) MemberExpr(STCE, false, FieldD, SourceLocation(),
3268 FieldD->getType(), VK_LValue,
3269 OK_Ordinary);
3270
3271 return ME;
3272}
3273
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003274Stmt *RewriteModernObjC::SynthMessageExpr(ObjCMessageExpr *Exp,
3275 SourceLocation StartLoc,
3276 SourceLocation EndLoc) {
3277 if (!SelGetUidFunctionDecl)
3278 SynthSelGetUidFunctionDecl();
3279 if (!MsgSendFunctionDecl)
3280 SynthMsgSendFunctionDecl();
3281 if (!MsgSendSuperFunctionDecl)
3282 SynthMsgSendSuperFunctionDecl();
3283 if (!MsgSendStretFunctionDecl)
3284 SynthMsgSendStretFunctionDecl();
3285 if (!MsgSendSuperStretFunctionDecl)
3286 SynthMsgSendSuperStretFunctionDecl();
3287 if (!MsgSendFpretFunctionDecl)
3288 SynthMsgSendFpretFunctionDecl();
3289 if (!GetClassFunctionDecl)
3290 SynthGetClassFunctionDecl();
3291 if (!GetSuperClassFunctionDecl)
3292 SynthGetSuperClassFunctionDecl();
3293 if (!GetMetaClassFunctionDecl)
3294 SynthGetMetaClassFunctionDecl();
3295
3296 // default to objc_msgSend().
3297 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
3298 // May need to use objc_msgSend_stret() as well.
3299 FunctionDecl *MsgSendStretFlavor = 0;
3300 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
3301 QualType resultType = mDecl->getResultType();
3302 if (resultType->isRecordType())
3303 MsgSendStretFlavor = MsgSendStretFunctionDecl;
3304 else if (resultType->isRealFloatingType())
3305 MsgSendFlavor = MsgSendFpretFunctionDecl;
3306 }
3307
3308 // Synthesize a call to objc_msgSend().
3309 SmallVector<Expr*, 8> MsgExprs;
3310 switch (Exp->getReceiverKind()) {
3311 case ObjCMessageExpr::SuperClass: {
3312 MsgSendFlavor = MsgSendSuperFunctionDecl;
3313 if (MsgSendStretFlavor)
3314 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
3315 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
3316
3317 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
3318
3319 SmallVector<Expr*, 4> InitExprs;
3320
3321 // set the receiver to self, the first argument to all methods.
3322 InitExprs.push_back(
3323 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3324 CK_BitCast,
3325 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCallf4b88a42012-03-10 09:33:50 +00003326 false,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003327 Context->getObjCIdType(),
3328 VK_RValue,
3329 SourceLocation()))
3330 ); // set the 'receiver'.
3331
3332 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3333 SmallVector<Expr*, 8> ClsExprs;
3334 QualType argType = Context->getPointerType(Context->CharTy);
3335 ClsExprs.push_back(StringLiteral::Create(*Context,
3336 ClassDecl->getIdentifier()->getName(),
3337 StringLiteral::Ascii, false,
3338 argType, SourceLocation()));
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00003339 // (Class)objc_getClass("CurrentClass")
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003340 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
3341 &ClsExprs[0],
3342 ClsExprs.size(),
3343 StartLoc,
3344 EndLoc);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003345 ClsExprs.clear();
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00003346 ClsExprs.push_back(Cls);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003347 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
3348 &ClsExprs[0], ClsExprs.size(),
3349 StartLoc, EndLoc);
3350
3351 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3352 // To turn off a warning, type-cast to 'id'
3353 InitExprs.push_back( // set 'super class', using class_getSuperclass().
3354 NoTypeInfoCStyleCastExpr(Context,
3355 Context->getObjCIdType(),
3356 CK_BitCast, Cls));
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003357 // struct __rw_objc_super
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003358 QualType superType = getSuperStructType();
3359 Expr *SuperRep;
3360
3361 if (LangOpts.MicrosoftExt) {
3362 SynthSuperContructorFunctionDecl();
3363 // Simulate a contructor call...
3364 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
John McCallf4b88a42012-03-10 09:33:50 +00003365 false, superType, VK_LValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003366 SourceLocation());
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003367 SuperRep = new (Context) CallExpr(*Context, DRE, InitExprs,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003368 superType, VK_LValue,
3369 SourceLocation());
3370 // The code for super is a little tricky to prevent collision with
3371 // the structure definition in the header. The rewriter has it's own
3372 // internal definition (__rw_objc_super) that is uses. This is why
3373 // we need the cast below. For example:
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003374 // (struct __rw_objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003375 //
3376 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
3377 Context->getPointerType(SuperRep->getType()),
3378 VK_RValue, OK_Ordinary,
3379 SourceLocation());
3380 SuperRep = NoTypeInfoCStyleCastExpr(Context,
3381 Context->getPointerType(superType),
3382 CK_BitCast, SuperRep);
3383 } else {
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003384 // (struct __rw_objc_super) { <exprs from above> }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003385 InitListExpr *ILE =
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003386 new (Context) InitListExpr(*Context, SourceLocation(), InitExprs,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003387 SourceLocation());
3388 TypeSourceInfo *superTInfo
3389 = Context->getTrivialTypeSourceInfo(superType);
3390 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
3391 superType, VK_LValue,
3392 ILE, false);
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003393 // struct __rw_objc_super *
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003394 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
3395 Context->getPointerType(SuperRep->getType()),
3396 VK_RValue, OK_Ordinary,
3397 SourceLocation());
3398 }
3399 MsgExprs.push_back(SuperRep);
3400 break;
3401 }
3402
3403 case ObjCMessageExpr::Class: {
3404 SmallVector<Expr*, 8> ClsExprs;
3405 QualType argType = Context->getPointerType(Context->CharTy);
3406 ObjCInterfaceDecl *Class
3407 = Exp->getClassReceiver()->getAs<ObjCObjectType>()->getInterface();
3408 IdentifierInfo *clsName = Class->getIdentifier();
3409 ClsExprs.push_back(StringLiteral::Create(*Context,
3410 clsName->getName(),
3411 StringLiteral::Ascii, false,
3412 argType, SourceLocation()));
3413 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
3414 &ClsExprs[0],
3415 ClsExprs.size(),
3416 StartLoc, EndLoc);
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00003417 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
3418 Context->getObjCIdType(),
3419 CK_BitCast, Cls);
3420 MsgExprs.push_back(ArgExpr);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003421 break;
3422 }
3423
3424 case ObjCMessageExpr::SuperInstance:{
3425 MsgSendFlavor = MsgSendSuperFunctionDecl;
3426 if (MsgSendStretFlavor)
3427 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
3428 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
3429 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
3430 SmallVector<Expr*, 4> InitExprs;
3431
3432 InitExprs.push_back(
3433 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3434 CK_BitCast,
3435 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCallf4b88a42012-03-10 09:33:50 +00003436 false,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003437 Context->getObjCIdType(),
3438 VK_RValue, SourceLocation()))
3439 ); // set the 'receiver'.
3440
3441 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3442 SmallVector<Expr*, 8> ClsExprs;
3443 QualType argType = Context->getPointerType(Context->CharTy);
3444 ClsExprs.push_back(StringLiteral::Create(*Context,
3445 ClassDecl->getIdentifier()->getName(),
3446 StringLiteral::Ascii, false, argType,
3447 SourceLocation()));
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00003448 // (Class)objc_getClass("CurrentClass")
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003449 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
3450 &ClsExprs[0],
3451 ClsExprs.size(),
3452 StartLoc, EndLoc);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003453 ClsExprs.clear();
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00003454 ClsExprs.push_back(Cls);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003455 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
3456 &ClsExprs[0], ClsExprs.size(),
3457 StartLoc, EndLoc);
3458
3459 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3460 // To turn off a warning, type-cast to 'id'
3461 InitExprs.push_back(
3462 // set 'super class', using class_getSuperclass().
3463 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3464 CK_BitCast, Cls));
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003465 // struct __rw_objc_super
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003466 QualType superType = getSuperStructType();
3467 Expr *SuperRep;
3468
3469 if (LangOpts.MicrosoftExt) {
3470 SynthSuperContructorFunctionDecl();
3471 // Simulate a contructor call...
3472 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
John McCallf4b88a42012-03-10 09:33:50 +00003473 false, superType, VK_LValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003474 SourceLocation());
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003475 SuperRep = new (Context) CallExpr(*Context, DRE, InitExprs,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003476 superType, VK_LValue, SourceLocation());
3477 // The code for super is a little tricky to prevent collision with
3478 // the structure definition in the header. The rewriter has it's own
3479 // internal definition (__rw_objc_super) that is uses. This is why
3480 // we need the cast below. For example:
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003481 // (struct __rw_objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003482 //
3483 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
3484 Context->getPointerType(SuperRep->getType()),
3485 VK_RValue, OK_Ordinary,
3486 SourceLocation());
3487 SuperRep = NoTypeInfoCStyleCastExpr(Context,
3488 Context->getPointerType(superType),
3489 CK_BitCast, SuperRep);
3490 } else {
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003491 // (struct __rw_objc_super) { <exprs from above> }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003492 InitListExpr *ILE =
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003493 new (Context) InitListExpr(*Context, SourceLocation(), InitExprs,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003494 SourceLocation());
3495 TypeSourceInfo *superTInfo
3496 = Context->getTrivialTypeSourceInfo(superType);
3497 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
3498 superType, VK_RValue, ILE,
3499 false);
3500 }
3501 MsgExprs.push_back(SuperRep);
3502 break;
3503 }
3504
3505 case ObjCMessageExpr::Instance: {
3506 // Remove all type-casts because it may contain objc-style types; e.g.
3507 // Foo<Proto> *.
3508 Expr *recExpr = Exp->getInstanceReceiver();
3509 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
3510 recExpr = CE->getSubExpr();
3511 CastKind CK = recExpr->getType()->isObjCObjectPointerType()
3512 ? CK_BitCast : recExpr->getType()->isBlockPointerType()
3513 ? CK_BlockPointerToObjCPointerCast
3514 : CK_CPointerToObjCPointerCast;
3515
3516 recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3517 CK, recExpr);
3518 MsgExprs.push_back(recExpr);
3519 break;
3520 }
3521 }
3522
3523 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
3524 SmallVector<Expr*, 8> SelExprs;
3525 QualType argType = Context->getPointerType(Context->CharTy);
3526 SelExprs.push_back(StringLiteral::Create(*Context,
3527 Exp->getSelector().getAsString(),
3528 StringLiteral::Ascii, false,
3529 argType, SourceLocation()));
3530 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
3531 &SelExprs[0], SelExprs.size(),
3532 StartLoc,
3533 EndLoc);
3534 MsgExprs.push_back(SelExp);
3535
3536 // Now push any user supplied arguments.
3537 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
3538 Expr *userExpr = Exp->getArg(i);
3539 // Make all implicit casts explicit...ICE comes in handy:-)
3540 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
3541 // Reuse the ICE type, it is exactly what the doctor ordered.
3542 QualType type = ICE->getType();
3543 if (needToScanForQualifiers(type))
3544 type = Context->getObjCIdType();
3545 // Make sure we convert "type (^)(...)" to "type (*)(...)".
3546 (void)convertBlockPointerToFunctionPointer(type);
3547 const Expr *SubExpr = ICE->IgnoreParenImpCasts();
3548 CastKind CK;
3549 if (SubExpr->getType()->isIntegralType(*Context) &&
3550 type->isBooleanType()) {
3551 CK = CK_IntegralToBoolean;
3552 } else if (type->isObjCObjectPointerType()) {
3553 if (SubExpr->getType()->isBlockPointerType()) {
3554 CK = CK_BlockPointerToObjCPointerCast;
3555 } else if (SubExpr->getType()->isPointerType()) {
3556 CK = CK_CPointerToObjCPointerCast;
3557 } else {
3558 CK = CK_BitCast;
3559 }
3560 } else {
3561 CK = CK_BitCast;
3562 }
3563
3564 userExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, userExpr);
3565 }
3566 // Make id<P...> cast into an 'id' cast.
3567 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
3568 if (CE->getType()->isObjCQualifiedIdType()) {
3569 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
3570 userExpr = CE->getSubExpr();
3571 CastKind CK;
3572 if (userExpr->getType()->isIntegralType(*Context)) {
3573 CK = CK_IntegralToPointer;
3574 } else if (userExpr->getType()->isBlockPointerType()) {
3575 CK = CK_BlockPointerToObjCPointerCast;
3576 } else if (userExpr->getType()->isPointerType()) {
3577 CK = CK_CPointerToObjCPointerCast;
3578 } else {
3579 CK = CK_BitCast;
3580 }
3581 userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3582 CK, userExpr);
3583 }
3584 }
3585 MsgExprs.push_back(userExpr);
3586 // We've transferred the ownership to MsgExprs. For now, we *don't* null
3587 // out the argument in the original expression (since we aren't deleting
3588 // the ObjCMessageExpr). See RewritePropertyOrImplicitSetter() usage for more info.
3589 //Exp->setArg(i, 0);
3590 }
3591 // Generate the funky cast.
3592 CastExpr *cast;
3593 SmallVector<QualType, 8> ArgTypes;
3594 QualType returnType;
3595
3596 // Push 'id' and 'SEL', the 2 implicit arguments.
3597 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
3598 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
3599 else
3600 ArgTypes.push_back(Context->getObjCIdType());
3601 ArgTypes.push_back(Context->getObjCSelType());
3602 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
3603 // Push any user argument types.
3604 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
3605 E = OMD->param_end(); PI != E; ++PI) {
3606 QualType t = (*PI)->getType()->isObjCQualifiedIdType()
3607 ? Context->getObjCIdType()
3608 : (*PI)->getType();
3609 // Make sure we convert "t (^)(...)" to "t (*)(...)".
3610 (void)convertBlockPointerToFunctionPointer(t);
3611 ArgTypes.push_back(t);
3612 }
3613 returnType = Exp->getType();
3614 convertToUnqualifiedObjCType(returnType);
3615 (void)convertBlockPointerToFunctionPointer(returnType);
3616 } else {
3617 returnType = Context->getObjCIdType();
3618 }
3619 // Get the type, we will need to reference it in a couple spots.
3620 QualType msgSendType = MsgSendFlavor->getType();
3621
3622 // Create a reference to the objc_msgSend() declaration.
John McCallf4b88a42012-03-10 09:33:50 +00003623 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003624 VK_LValue, SourceLocation());
3625
3626 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
3627 // If we don't do this cast, we get the following bizarre warning/note:
3628 // xx.m:13: warning: function called through a non-compatible type
3629 // xx.m:13: note: if this code is reached, the program will abort
3630 cast = NoTypeInfoCStyleCastExpr(Context,
3631 Context->getPointerType(Context->VoidTy),
3632 CK_BitCast, DRE);
3633
3634 // Now do the "normal" pointer to function cast.
3635 QualType castType =
3636 getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
3637 // If we don't have a method decl, force a variadic cast.
3638 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true);
3639 castType = Context->getPointerType(castType);
3640 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
3641 cast);
3642
3643 // Don't forget the parens to enforce the proper binding.
3644 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
3645
3646 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003647 CallExpr *CE = new (Context) CallExpr(*Context, PE, MsgExprs,
3648 FT->getResultType(), VK_RValue, EndLoc);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003649 Stmt *ReplacingStmt = CE;
3650 if (MsgSendStretFlavor) {
3651 // We have the method which returns a struct/union. Must also generate
3652 // call to objc_msgSend_stret and hang both varieties on a conditional
3653 // expression which dictate which one to envoke depending on size of
3654 // method's return type.
3655
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +00003656 Expr *STCE = SynthMsgSendStretCallExpr(MsgSendStretFlavor,
3657 msgSendType, returnType,
3658 ArgTypes, MsgExprs,
3659 Exp->getMethodDecl());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003660
3661 // Build sizeof(returnType)
3662 UnaryExprOrTypeTraitExpr *sizeofExpr =
3663 new (Context) UnaryExprOrTypeTraitExpr(UETT_SizeOf,
3664 Context->getTrivialTypeSourceInfo(returnType),
3665 Context->getSizeType(), SourceLocation(),
3666 SourceLocation());
3667 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
3668 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
3669 // For X86 it is more complicated and some kind of target specific routine
3670 // is needed to decide what to do.
3671 unsigned IntSize =
3672 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
3673 IntegerLiteral *limit = IntegerLiteral::Create(*Context,
3674 llvm::APInt(IntSize, 8),
3675 Context->IntTy,
3676 SourceLocation());
3677 BinaryOperator *lessThanExpr =
3678 new (Context) BinaryOperator(sizeofExpr, limit, BO_LE, Context->IntTy,
Lang Hamesbe9af122012-10-02 04:45:10 +00003679 VK_RValue, OK_Ordinary, SourceLocation(),
3680 false);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003681 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
3682 ConditionalOperator *CondExpr =
3683 new (Context) ConditionalOperator(lessThanExpr,
3684 SourceLocation(), CE,
3685 SourceLocation(), STCE,
3686 returnType, VK_RValue, OK_Ordinary);
3687 ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3688 CondExpr);
3689 }
3690 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3691 return ReplacingStmt;
3692}
3693
3694Stmt *RewriteModernObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
3695 Stmt *ReplacingStmt = SynthMessageExpr(Exp, Exp->getLocStart(),
3696 Exp->getLocEnd());
3697
3698 // Now do the actual rewrite.
3699 ReplaceStmt(Exp, ReplacingStmt);
3700
3701 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3702 return ReplacingStmt;
3703}
3704
3705// typedef struct objc_object Protocol;
3706QualType RewriteModernObjC::getProtocolType() {
3707 if (!ProtocolTypeDecl) {
3708 TypeSourceInfo *TInfo
3709 = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
3710 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
3711 SourceLocation(), SourceLocation(),
3712 &Context->Idents.get("Protocol"),
3713 TInfo);
3714 }
3715 return Context->getTypeDeclType(ProtocolTypeDecl);
3716}
3717
3718/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
3719/// a synthesized/forward data reference (to the protocol's metadata).
3720/// The forward references (and metadata) are generated in
3721/// RewriteModernObjC::HandleTranslationUnit().
3722Stmt *RewriteModernObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00003723 std::string Name = "_OBJC_PROTOCOL_REFERENCE_$_" +
3724 Exp->getProtocol()->getNameAsString();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003725 IdentifierInfo *ID = &Context->Idents.get(Name);
3726 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
3727 SourceLocation(), ID, getProtocolType(), 0,
3728 SC_Extern, SC_None);
John McCallf4b88a42012-03-10 09:33:50 +00003729 DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, false, getProtocolType(),
3730 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003731 Expr *DerefExpr = new (Context) UnaryOperator(DRE, UO_AddrOf,
3732 Context->getPointerType(DRE->getType()),
3733 VK_RValue, OK_Ordinary, SourceLocation());
3734 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, DerefExpr->getType(),
3735 CK_BitCast,
3736 DerefExpr);
3737 ReplaceStmt(Exp, castExpr);
3738 ProtocolExprDecls.insert(Exp->getProtocol()->getCanonicalDecl());
3739 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3740 return castExpr;
3741
3742}
3743
3744bool RewriteModernObjC::BufferContainsPPDirectives(const char *startBuf,
3745 const char *endBuf) {
3746 while (startBuf < endBuf) {
3747 if (*startBuf == '#') {
3748 // Skip whitespace.
3749 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
3750 ;
3751 if (!strncmp(startBuf, "if", strlen("if")) ||
3752 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
3753 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
3754 !strncmp(startBuf, "define", strlen("define")) ||
3755 !strncmp(startBuf, "undef", strlen("undef")) ||
3756 !strncmp(startBuf, "else", strlen("else")) ||
3757 !strncmp(startBuf, "elif", strlen("elif")) ||
3758 !strncmp(startBuf, "endif", strlen("endif")) ||
3759 !strncmp(startBuf, "pragma", strlen("pragma")) ||
3760 !strncmp(startBuf, "include", strlen("include")) ||
3761 !strncmp(startBuf, "import", strlen("import")) ||
3762 !strncmp(startBuf, "include_next", strlen("include_next")))
3763 return true;
3764 }
3765 startBuf++;
3766 }
3767 return false;
3768}
3769
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003770/// IsTagDefinedInsideClass - This routine checks that a named tagged type
3771/// is defined inside an objective-c class. If so, it returns true.
Fariborz Jahanianb68258f2012-05-01 17:46:45 +00003772bool RewriteModernObjC::IsTagDefinedInsideClass(ObjCContainerDecl *IDecl,
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003773 TagDecl *Tag,
3774 bool &IsNamedDefinition) {
Fariborz Jahanian89585e802012-04-30 19:46:53 +00003775 if (!IDecl)
3776 return false;
3777 SourceLocation TagLocation;
3778 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) {
3779 RD = RD->getDefinition();
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003780 if (!RD || !RD->getDeclName().getAsIdentifierInfo())
Fariborz Jahanian89585e802012-04-30 19:46:53 +00003781 return false;
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003782 IsNamedDefinition = true;
Fariborz Jahanian89585e802012-04-30 19:46:53 +00003783 TagLocation = RD->getLocation();
3784 return Context->getSourceManager().isBeforeInTranslationUnit(
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003785 IDecl->getLocation(), TagLocation);
3786 }
3787 if (EnumDecl *ED = dyn_cast<EnumDecl>(Tag)) {
3788 if (!ED || !ED->getDeclName().getAsIdentifierInfo())
3789 return false;
3790 IsNamedDefinition = true;
3791 TagLocation = ED->getLocation();
3792 return Context->getSourceManager().isBeforeInTranslationUnit(
3793 IDecl->getLocation(), TagLocation);
3794
Fariborz Jahanian89585e802012-04-30 19:46:53 +00003795 }
3796 return false;
3797}
3798
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003799/// RewriteObjCFieldDeclType - This routine rewrites a type into the buffer.
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003800/// It handles elaborated types, as well as enum types in the process.
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003801bool RewriteModernObjC::RewriteObjCFieldDeclType(QualType &Type,
3802 std::string &Result) {
Fariborz Jahanianf5eac482012-05-02 17:34:59 +00003803 if (isa<TypedefType>(Type)) {
3804 Result += "\t";
3805 return false;
3806 }
3807
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003808 if (Type->isArrayType()) {
3809 QualType ElemTy = Context->getBaseElementType(Type);
3810 return RewriteObjCFieldDeclType(ElemTy, Result);
3811 }
3812 else if (Type->isRecordType()) {
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003813 RecordDecl *RD = Type->getAs<RecordType>()->getDecl();
3814 if (RD->isCompleteDefinition()) {
3815 if (RD->isStruct())
3816 Result += "\n\tstruct ";
3817 else if (RD->isUnion())
3818 Result += "\n\tunion ";
3819 else
3820 assert(false && "class not allowed as an ivar type");
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003821
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003822 Result += RD->getName();
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003823 if (GlobalDefinedTags.count(RD)) {
3824 // struct/union is defined globally, use it.
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003825 Result += " ";
3826 return true;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003827 }
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003828 Result += " {\n";
3829 for (RecordDecl::field_iterator i = RD->field_begin(),
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003830 e = RD->field_end(); i != e; ++i) {
David Blaikie581deb32012-06-06 20:45:41 +00003831 FieldDecl *FD = *i;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003832 RewriteObjCFieldDecl(FD, Result);
3833 }
3834 Result += "\t} ";
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003835 return true;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003836 }
3837 }
3838 else if (Type->isEnumeralType()) {
3839 EnumDecl *ED = Type->getAs<EnumType>()->getDecl();
3840 if (ED->isCompleteDefinition()) {
3841 Result += "\n\tenum ";
3842 Result += ED->getName();
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003843 if (GlobalDefinedTags.count(ED)) {
3844 // Enum is globall defined, use it.
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003845 Result += " ";
3846 return true;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003847 }
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003848
3849 Result += " {\n";
3850 for (EnumDecl::enumerator_iterator EC = ED->enumerator_begin(),
3851 ECEnd = ED->enumerator_end(); EC != ECEnd; ++EC) {
3852 Result += "\t"; Result += EC->getName(); Result += " = ";
3853 llvm::APSInt Val = EC->getInitVal();
3854 Result += Val.toString(10);
3855 Result += ",\n";
3856 }
3857 Result += "\t} ";
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003858 return true;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003859 }
3860 }
3861
3862 Result += "\t";
3863 convertObjCTypeToCStyleType(Type);
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003864 return false;
3865}
3866
3867
3868/// RewriteObjCFieldDecl - This routine rewrites a field into the buffer.
3869/// It handles elaborated types, as well as enum types in the process.
3870void RewriteModernObjC::RewriteObjCFieldDecl(FieldDecl *fieldDecl,
3871 std::string &Result) {
3872 QualType Type = fieldDecl->getType();
3873 std::string Name = fieldDecl->getNameAsString();
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003874
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003875 bool EleboratedType = RewriteObjCFieldDeclType(Type, Result);
3876 if (!EleboratedType)
3877 Type.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003878 Result += Name;
3879 if (fieldDecl->isBitField()) {
3880 Result += " : "; Result += utostr(fieldDecl->getBitWidthValue(*Context));
3881 }
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003882 else if (EleboratedType && Type->isArrayType()) {
Eli Friedman6febf122012-12-13 01:43:21 +00003883 const ArrayType *AT = Context->getAsArrayType(Type);
3884 do {
3885 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003886 Result += "[";
3887 llvm::APInt Dim = CAT->getSize();
3888 Result += utostr(Dim.getZExtValue());
3889 Result += "]";
3890 }
Eli Friedman6febf122012-12-13 01:43:21 +00003891 AT = Context->getAsArrayType(AT->getElementType());
3892 } while (AT);
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003893 }
3894
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003895 Result += ";\n";
3896}
3897
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003898/// RewriteLocallyDefinedNamedAggregates - This routine rewrites locally defined
3899/// named aggregate types into the input buffer.
3900void RewriteModernObjC::RewriteLocallyDefinedNamedAggregates(FieldDecl *fieldDecl,
3901 std::string &Result) {
3902 QualType Type = fieldDecl->getType();
Fariborz Jahanianf5eac482012-05-02 17:34:59 +00003903 if (isa<TypedefType>(Type))
3904 return;
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003905 if (Type->isArrayType())
3906 Type = Context->getBaseElementType(Type);
Fariborz Jahanianb68258f2012-05-01 17:46:45 +00003907 ObjCContainerDecl *IDecl =
3908 dyn_cast<ObjCContainerDecl>(fieldDecl->getDeclContext());
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003909
3910 TagDecl *TD = 0;
3911 if (Type->isRecordType()) {
3912 TD = Type->getAs<RecordType>()->getDecl();
3913 }
3914 else if (Type->isEnumeralType()) {
3915 TD = Type->getAs<EnumType>()->getDecl();
3916 }
3917
3918 if (TD) {
3919 if (GlobalDefinedTags.count(TD))
3920 return;
3921
3922 bool IsNamedDefinition = false;
3923 if (IsTagDefinedInsideClass(IDecl, TD, IsNamedDefinition)) {
3924 RewriteObjCFieldDeclType(Type, Result);
3925 Result += ";";
3926 }
3927 if (IsNamedDefinition)
3928 GlobalDefinedTags.insert(TD);
3929 }
3930
3931}
3932
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00003933unsigned RewriteModernObjC::ObjCIvarBitfieldGroupNo(ObjCIvarDecl *IV) {
3934 const ObjCInterfaceDecl *CDecl = IV->getContainingInterface();
3935 if (ObjCInterefaceHasBitfieldGroups.count(CDecl)) {
3936 return IvarGroupNumber[IV];
3937 }
3938 unsigned GroupNo = 0;
3939 SmallVector<const ObjCIvarDecl *, 8> IVars;
3940 for (const ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
3941 IVD; IVD = IVD->getNextIvar())
3942 IVars.push_back(IVD);
3943
3944 for (unsigned i = 0, e = IVars.size(); i < e; i++)
3945 if (IVars[i]->isBitField()) {
3946 IvarGroupNumber[IVars[i++]] = ++GroupNo;
3947 while (i < e && IVars[i]->isBitField())
3948 IvarGroupNumber[IVars[i++]] = GroupNo;
3949 if (i < e)
3950 --i;
3951 }
3952
3953 ObjCInterefaceHasBitfieldGroups.insert(CDecl);
3954 return IvarGroupNumber[IV];
3955}
3956
3957QualType RewriteModernObjC::SynthesizeBitfieldGroupStructType(
3958 ObjCIvarDecl *IV,
3959 SmallVectorImpl<ObjCIvarDecl *> &IVars) {
3960 std::string StructTagName;
3961 ObjCIvarBitfieldGroupType(IV, StructTagName);
3962 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct,
3963 Context->getTranslationUnitDecl(),
3964 SourceLocation(), SourceLocation(),
3965 &Context->Idents.get(StructTagName));
3966 for (unsigned i=0, e = IVars.size(); i < e; i++) {
3967 ObjCIvarDecl *Ivar = IVars[i];
3968 RD->addDecl(FieldDecl::Create(*Context, RD, SourceLocation(), SourceLocation(),
3969 &Context->Idents.get(Ivar->getName()),
3970 Ivar->getType(),
3971 0, /*Expr *BW */Ivar->getBitWidth(), false,
3972 ICIS_NoInit));
3973 }
3974 RD->completeDefinition();
3975 return Context->getTagDeclType(RD);
3976}
3977
3978QualType RewriteModernObjC::GetGroupRecordTypeForObjCIvarBitfield(ObjCIvarDecl *IV) {
3979 const ObjCInterfaceDecl *CDecl = IV->getContainingInterface();
3980 unsigned GroupNo = ObjCIvarBitfieldGroupNo(IV);
3981 std::pair<const ObjCInterfaceDecl*, unsigned> tuple = std::make_pair(CDecl, GroupNo);
3982 if (GroupRecordType.count(tuple))
3983 return GroupRecordType[tuple];
3984
3985 SmallVector<ObjCIvarDecl *, 8> IVars;
3986 for (const ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
3987 IVD; IVD = IVD->getNextIvar()) {
3988 if (IVD->isBitField())
3989 IVars.push_back(const_cast<ObjCIvarDecl *>(IVD));
3990 else {
3991 if (!IVars.empty()) {
3992 unsigned GroupNo = ObjCIvarBitfieldGroupNo(IVars[0]);
3993 // Generate the struct type for this group of bitfield ivars.
3994 GroupRecordType[std::make_pair(CDecl, GroupNo)] =
3995 SynthesizeBitfieldGroupStructType(IVars[0], IVars);
3996 IVars.clear();
3997 }
3998 }
3999 }
4000 if (!IVars.empty()) {
4001 // Do the last one.
4002 unsigned GroupNo = ObjCIvarBitfieldGroupNo(IVars[0]);
4003 GroupRecordType[std::make_pair(CDecl, GroupNo)] =
4004 SynthesizeBitfieldGroupStructType(IVars[0], IVars);
4005 }
4006 QualType RetQT = GroupRecordType[tuple];
4007 assert(!RetQT.isNull() && "GetGroupRecordTypeForObjCIvarBitfield struct type is NULL");
4008
4009 return RetQT;
4010}
4011
4012/// ObjCIvarBitfieldGroupDecl - Names field decl. for ivar bitfield group.
4013/// Name would be: classname__GRBF_n where n is the group number for this ivar.
4014void RewriteModernObjC::ObjCIvarBitfieldGroupDecl(ObjCIvarDecl *IV,
4015 std::string &Result) {
4016 const ObjCInterfaceDecl *CDecl = IV->getContainingInterface();
4017 Result += CDecl->getName();
4018 Result += "__GRBF_";
4019 unsigned GroupNo = ObjCIvarBitfieldGroupNo(IV);
4020 Result += utostr(GroupNo);
4021 return;
4022}
4023
4024/// ObjCIvarBitfieldGroupType - Names struct type for ivar bitfield group.
4025/// Name of the struct would be: classname__T_n where n is the group number for
4026/// this ivar.
4027void RewriteModernObjC::ObjCIvarBitfieldGroupType(ObjCIvarDecl *IV,
4028 std::string &Result) {
4029 const ObjCInterfaceDecl *CDecl = IV->getContainingInterface();
4030 Result += CDecl->getName();
4031 Result += "__T_";
4032 unsigned GroupNo = ObjCIvarBitfieldGroupNo(IV);
4033 Result += utostr(GroupNo);
4034 return;
4035}
4036
4037/// ObjCIvarBitfieldGroupOffset - Names symbol for ivar bitfield group field offset.
4038/// Name would be: OBJC_IVAR_$_classname__GRBF_n where n is the group number for
4039/// this ivar.
4040void RewriteModernObjC::ObjCIvarBitfieldGroupOffset(ObjCIvarDecl *IV,
4041 std::string &Result) {
4042 Result += "OBJC_IVAR_$_";
4043 ObjCIvarBitfieldGroupDecl(IV, Result);
4044}
4045
4046#define SKIP_BITFIELDS(IX, ENDIX, VEC) { \
4047 while ((IX < ENDIX) && VEC[IX]->isBitField()) \
4048 ++IX; \
4049 if (IX < ENDIX) \
4050 --IX; \
4051}
4052
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004053/// RewriteObjCInternalStruct - Rewrite one internal struct corresponding to
4054/// an objective-c class with ivars.
4055void RewriteModernObjC::RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
4056 std::string &Result) {
4057 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
4058 assert(CDecl->getName() != "" &&
4059 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004060 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00004061 SmallVector<ObjCIvarDecl *, 8> IVars;
4062 for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
Fariborz Jahanian9a2105b2012-03-06 17:16:27 +00004063 IVD; IVD = IVD->getNextIvar())
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00004064 IVars.push_back(IVD);
Fariborz Jahanian9a2105b2012-03-06 17:16:27 +00004065
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004066 SourceLocation LocStart = CDecl->getLocStart();
4067 SourceLocation LocEnd = CDecl->getEndOfDefinitionLoc();
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00004068
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004069 const char *startBuf = SM->getCharacterData(LocStart);
4070 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00004071
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004072 // If no ivars and no root or if its root, directly or indirectly,
4073 // have no ivars (thus not synthesized) then no need to synthesize this class.
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00004074 if ((!CDecl->isThisDeclarationADefinition() || IVars.size() == 0) &&
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004075 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
4076 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
4077 ReplaceText(LocStart, endBuf-startBuf, Result);
4078 return;
4079 }
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00004080
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00004081 // Insert named struct/union definitions inside class to
4082 // outer scope. This follows semantics of locally defined
4083 // struct/unions in objective-c classes.
4084 for (unsigned i = 0, e = IVars.size(); i < e; i++)
4085 RewriteLocallyDefinedNamedAggregates(IVars[i], Result);
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00004086
4087 // Insert named structs which are syntheized to group ivar bitfields
4088 // to outer scope as well.
4089 for (unsigned i = 0, e = IVars.size(); i < e; i++)
4090 if (IVars[i]->isBitField()) {
4091 ObjCIvarDecl *IV = IVars[i];
4092 QualType QT = GetGroupRecordTypeForObjCIvarBitfield(IV);
4093 RewriteObjCFieldDeclType(QT, Result);
4094 Result += ";";
4095 // skip over ivar bitfields in this group.
4096 SKIP_BITFIELDS(i , e, IVars);
4097 }
4098
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004099 Result += "\nstruct ";
4100 Result += CDecl->getNameAsString();
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00004101 Result += "_IMPL {\n";
4102
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00004103 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00004104 Result += "\tstruct "; Result += RCDecl->getNameAsString();
4105 Result += "_IMPL "; Result += RCDecl->getNameAsString();
4106 Result += "_IVARS;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004107 }
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00004108
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00004109 for (unsigned i = 0, e = IVars.size(); i < e; i++) {
4110 if (IVars[i]->isBitField()) {
4111 ObjCIvarDecl *IV = IVars[i];
4112 Result += "\tstruct ";
4113 ObjCIvarBitfieldGroupType(IV, Result); Result += " ";
4114 ObjCIvarBitfieldGroupDecl(IV, Result); Result += ";\n";
4115 // skip over ivar bitfields in this group.
4116 SKIP_BITFIELDS(i , e, IVars);
4117 }
4118 else
4119 RewriteObjCFieldDecl(IVars[i], Result);
4120 }
Fariborz Jahanian0b17b9a2012-02-12 21:36:23 +00004121
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00004122 Result += "};\n";
4123 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
4124 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00004125 // Mark this struct as having been generated.
4126 if (!ObjCSynthesizedStructs.insert(CDecl))
4127 llvm_unreachable("struct already synthesize- RewriteObjCInternalStruct");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004128}
4129
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00004130/// RewriteIvarOffsetSymbols - Rewrite ivar offset symbols of those ivars which
4131/// have been referenced in an ivar access expression.
4132void RewriteModernObjC::RewriteIvarOffsetSymbols(ObjCInterfaceDecl *CDecl,
4133 std::string &Result) {
4134 // write out ivar offset symbols which have been referenced in an ivar
4135 // access expression.
4136 llvm::SmallPtrSet<ObjCIvarDecl *, 8> Ivars = ReferencedIvars[CDecl];
4137 if (Ivars.empty())
4138 return;
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00004139
4140 llvm::DenseSet<std::pair<const ObjCInterfaceDecl*, unsigned> > GroupSymbolOutput;
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00004141 for (llvm::SmallPtrSet<ObjCIvarDecl *, 8>::iterator i = Ivars.begin(),
4142 e = Ivars.end(); i != e; i++) {
4143 ObjCIvarDecl *IvarDecl = (*i);
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00004144 const ObjCInterfaceDecl *IDecl = IvarDecl->getContainingInterface();
4145 unsigned GroupNo = 0;
4146 if (IvarDecl->isBitField()) {
4147 GroupNo = ObjCIvarBitfieldGroupNo(IvarDecl);
4148 if (GroupSymbolOutput.count(std::make_pair(IDecl, GroupNo)))
4149 continue;
4150 }
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00004151 Result += "\n";
4152 if (LangOpts.MicrosoftExt)
4153 Result += "__declspec(allocate(\".objc_ivar$B\")) ";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00004154 Result += "extern \"C\" ";
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00004155 if (LangOpts.MicrosoftExt &&
4156 IvarDecl->getAccessControl() != ObjCIvarDecl::Private &&
Fariborz Jahanian297976d2012-03-29 17:51:09 +00004157 IvarDecl->getAccessControl() != ObjCIvarDecl::Package)
4158 Result += "__declspec(dllimport) ";
4159
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00004160 Result += "unsigned long ";
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00004161 if (IvarDecl->isBitField()) {
4162 ObjCIvarBitfieldGroupOffset(IvarDecl, Result);
4163 GroupSymbolOutput.insert(std::make_pair(IDecl, GroupNo));
4164 }
4165 else
4166 WriteInternalIvarName(CDecl, IvarDecl, Result);
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00004167 Result += ";";
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00004168 }
4169}
4170
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004171//===----------------------------------------------------------------------===//
4172// Meta Data Emission
4173//===----------------------------------------------------------------------===//
4174
4175
4176/// RewriteImplementations - This routine rewrites all method implementations
4177/// and emits meta-data.
4178
4179void RewriteModernObjC::RewriteImplementations() {
4180 int ClsDefCount = ClassImplementation.size();
4181 int CatDefCount = CategoryImplementation.size();
4182
4183 // Rewrite implemented methods
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00004184 for (int i = 0; i < ClsDefCount; i++) {
4185 ObjCImplementationDecl *OIMP = ClassImplementation[i];
4186 ObjCInterfaceDecl *CDecl = OIMP->getClassInterface();
4187 if (CDecl->isImplicitInterfaceDecl())
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +00004188 assert(false &&
4189 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00004190 RewriteImplementationDecl(OIMP);
4191 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004192
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00004193 for (int i = 0; i < CatDefCount; i++) {
4194 ObjCCategoryImplDecl *CIMP = CategoryImplementation[i];
4195 ObjCInterfaceDecl *CDecl = CIMP->getClassInterface();
4196 if (CDecl->isImplicitInterfaceDecl())
4197 assert(false &&
4198 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00004199 RewriteImplementationDecl(CIMP);
4200 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004201}
4202
4203void RewriteModernObjC::RewriteByRefString(std::string &ResultStr,
4204 const std::string &Name,
4205 ValueDecl *VD, bool def) {
4206 assert(BlockByRefDeclNo.count(VD) &&
4207 "RewriteByRefString: ByRef decl missing");
4208 if (def)
4209 ResultStr += "struct ";
4210 ResultStr += "__Block_byref_" + Name +
4211 "_" + utostr(BlockByRefDeclNo[VD]) ;
4212}
4213
4214static bool HasLocalVariableExternalStorage(ValueDecl *VD) {
4215 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4216 return (Var->isFunctionOrMethodVarDecl() && !Var->hasLocalStorage());
4217 return false;
4218}
4219
4220std::string RewriteModernObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
4221 StringRef funcName,
4222 std::string Tag) {
4223 const FunctionType *AFT = CE->getFunctionType();
4224 QualType RT = AFT->getResultType();
4225 std::string StructRef = "struct " + Tag;
Fariborz Jahanianf616ae22012-11-06 23:25:49 +00004226 SourceLocation BlockLoc = CE->getExprLoc();
4227 std::string S;
4228 ConvertSourceLocationToLineDirective(BlockLoc, S);
4229
4230 S += "static " + RT.getAsString(Context->getPrintingPolicy()) + " __" +
4231 funcName.str() + "_block_func_" + utostr(i);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004232
4233 BlockDecl *BD = CE->getBlockDecl();
4234
4235 if (isa<FunctionNoProtoType>(AFT)) {
4236 // No user-supplied arguments. Still need to pass in a pointer to the
4237 // block (to reference imported block decl refs).
4238 S += "(" + StructRef + " *__cself)";
4239 } else if (BD->param_empty()) {
4240 S += "(" + StructRef + " *__cself)";
4241 } else {
4242 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
4243 assert(FT && "SynthesizeBlockFunc: No function proto");
4244 S += '(';
4245 // first add the implicit argument.
4246 S += StructRef + " *__cself, ";
4247 std::string ParamStr;
4248 for (BlockDecl::param_iterator AI = BD->param_begin(),
4249 E = BD->param_end(); AI != E; ++AI) {
4250 if (AI != BD->param_begin()) S += ", ";
4251 ParamStr = (*AI)->getNameAsString();
4252 QualType QT = (*AI)->getType();
Fariborz Jahanian2610f902012-03-27 16:42:20 +00004253 (void)convertBlockPointerToFunctionPointer(QT);
4254 QT.getAsStringInternal(ParamStr, Context->getPrintingPolicy());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004255 S += ParamStr;
4256 }
4257 if (FT->isVariadic()) {
4258 if (!BD->param_empty()) S += ", ";
4259 S += "...";
4260 }
4261 S += ')';
4262 }
4263 S += " {\n";
4264
4265 // Create local declarations to avoid rewriting all closure decl ref exprs.
4266 // First, emit a declaration for all "by ref" decls.
4267 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
4268 E = BlockByRefDecls.end(); I != E; ++I) {
4269 S += " ";
4270 std::string Name = (*I)->getNameAsString();
4271 std::string TypeString;
4272 RewriteByRefString(TypeString, Name, (*I));
4273 TypeString += " *";
4274 Name = TypeString + Name;
4275 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
4276 }
4277 // Next, emit a declaration for all "by copy" declarations.
4278 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
4279 E = BlockByCopyDecls.end(); I != E; ++I) {
4280 S += " ";
4281 // Handle nested closure invocation. For example:
4282 //
4283 // void (^myImportedClosure)(void);
4284 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
4285 //
4286 // void (^anotherClosure)(void);
4287 // anotherClosure = ^(void) {
4288 // myImportedClosure(); // import and invoke the closure
4289 // };
4290 //
4291 if (isTopLevelBlockPointerType((*I)->getType())) {
4292 RewriteBlockPointerTypeVariable(S, (*I));
4293 S += " = (";
4294 RewriteBlockPointerType(S, (*I)->getType());
4295 S += ")";
4296 S += "__cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
4297 }
4298 else {
4299 std::string Name = (*I)->getNameAsString();
4300 QualType QT = (*I)->getType();
4301 if (HasLocalVariableExternalStorage(*I))
4302 QT = Context->getPointerType(QT);
4303 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
4304 S += Name + " = __cself->" +
4305 (*I)->getNameAsString() + "; // bound by copy\n";
4306 }
4307 }
4308 std::string RewrittenStr = RewrittenBlockExprs[CE];
4309 const char *cstr = RewrittenStr.c_str();
4310 while (*cstr++ != '{') ;
4311 S += cstr;
4312 S += "\n";
4313 return S;
4314}
4315
4316std::string RewriteModernObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
4317 StringRef funcName,
4318 std::string Tag) {
4319 std::string StructRef = "struct " + Tag;
4320 std::string S = "static void __";
4321
4322 S += funcName;
4323 S += "_block_copy_" + utostr(i);
4324 S += "(" + StructRef;
4325 S += "*dst, " + StructRef;
4326 S += "*src) {";
4327 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
4328 E = ImportedBlockDecls.end(); I != E; ++I) {
4329 ValueDecl *VD = (*I);
4330 S += "_Block_object_assign((void*)&dst->";
4331 S += (*I)->getNameAsString();
4332 S += ", (void*)src->";
4333 S += (*I)->getNameAsString();
4334 if (BlockByRefDeclsPtrSet.count((*I)))
4335 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
4336 else if (VD->getType()->isBlockPointerType())
4337 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
4338 else
4339 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
4340 }
4341 S += "}\n";
4342
4343 S += "\nstatic void __";
4344 S += funcName;
4345 S += "_block_dispose_" + utostr(i);
4346 S += "(" + StructRef;
4347 S += "*src) {";
4348 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
4349 E = ImportedBlockDecls.end(); I != E; ++I) {
4350 ValueDecl *VD = (*I);
4351 S += "_Block_object_dispose((void*)src->";
4352 S += (*I)->getNameAsString();
4353 if (BlockByRefDeclsPtrSet.count((*I)))
4354 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
4355 else if (VD->getType()->isBlockPointerType())
4356 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
4357 else
4358 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
4359 }
4360 S += "}\n";
4361 return S;
4362}
4363
4364std::string RewriteModernObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
4365 std::string Desc) {
4366 std::string S = "\nstruct " + Tag;
4367 std::string Constructor = " " + Tag;
4368
4369 S += " {\n struct __block_impl impl;\n";
4370 S += " struct " + Desc;
4371 S += "* Desc;\n";
4372
4373 Constructor += "(void *fp, "; // Invoke function pointer.
4374 Constructor += "struct " + Desc; // Descriptor pointer.
4375 Constructor += " *desc";
4376
4377 if (BlockDeclRefs.size()) {
4378 // Output all "by copy" declarations.
4379 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
4380 E = BlockByCopyDecls.end(); I != E; ++I) {
4381 S += " ";
4382 std::string FieldName = (*I)->getNameAsString();
4383 std::string ArgName = "_" + FieldName;
4384 // Handle nested closure invocation. For example:
4385 //
4386 // void (^myImportedBlock)(void);
4387 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
4388 //
4389 // void (^anotherBlock)(void);
4390 // anotherBlock = ^(void) {
4391 // myImportedBlock(); // import and invoke the closure
4392 // };
4393 //
4394 if (isTopLevelBlockPointerType((*I)->getType())) {
4395 S += "struct __block_impl *";
4396 Constructor += ", void *" + ArgName;
4397 } else {
4398 QualType QT = (*I)->getType();
4399 if (HasLocalVariableExternalStorage(*I))
4400 QT = Context->getPointerType(QT);
4401 QT.getAsStringInternal(FieldName, Context->getPrintingPolicy());
4402 QT.getAsStringInternal(ArgName, Context->getPrintingPolicy());
4403 Constructor += ", " + ArgName;
4404 }
4405 S += FieldName + ";\n";
4406 }
4407 // Output all "by ref" declarations.
4408 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
4409 E = BlockByRefDecls.end(); I != E; ++I) {
4410 S += " ";
4411 std::string FieldName = (*I)->getNameAsString();
4412 std::string ArgName = "_" + FieldName;
4413 {
4414 std::string TypeString;
4415 RewriteByRefString(TypeString, FieldName, (*I));
4416 TypeString += " *";
4417 FieldName = TypeString + FieldName;
4418 ArgName = TypeString + ArgName;
4419 Constructor += ", " + ArgName;
4420 }
4421 S += FieldName + "; // by ref\n";
4422 }
4423 // Finish writing the constructor.
4424 Constructor += ", int flags=0)";
4425 // Initialize all "by copy" arguments.
4426 bool firsTime = true;
4427 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
4428 E = BlockByCopyDecls.end(); I != E; ++I) {
4429 std::string Name = (*I)->getNameAsString();
4430 if (firsTime) {
4431 Constructor += " : ";
4432 firsTime = false;
4433 }
4434 else
4435 Constructor += ", ";
4436 if (isTopLevelBlockPointerType((*I)->getType()))
4437 Constructor += Name + "((struct __block_impl *)_" + Name + ")";
4438 else
4439 Constructor += Name + "(_" + Name + ")";
4440 }
4441 // Initialize all "by ref" arguments.
4442 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
4443 E = BlockByRefDecls.end(); I != E; ++I) {
4444 std::string Name = (*I)->getNameAsString();
4445 if (firsTime) {
4446 Constructor += " : ";
4447 firsTime = false;
4448 }
4449 else
4450 Constructor += ", ";
4451 Constructor += Name + "(_" + Name + "->__forwarding)";
4452 }
4453
4454 Constructor += " {\n";
4455 if (GlobalVarDecl)
4456 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4457 else
4458 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
4459 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
4460
4461 Constructor += " Desc = desc;\n";
4462 } else {
4463 // Finish writing the constructor.
4464 Constructor += ", int flags=0) {\n";
4465 if (GlobalVarDecl)
4466 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4467 else
4468 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
4469 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
4470 Constructor += " Desc = desc;\n";
4471 }
4472 Constructor += " ";
4473 Constructor += "}\n";
4474 S += Constructor;
4475 S += "};\n";
4476 return S;
4477}
4478
4479std::string RewriteModernObjC::SynthesizeBlockDescriptor(std::string DescTag,
4480 std::string ImplTag, int i,
4481 StringRef FunName,
4482 unsigned hasCopy) {
4483 std::string S = "\nstatic struct " + DescTag;
4484
Fariborz Jahanian8b08adb2012-05-03 21:44:12 +00004485 S += " {\n size_t reserved;\n";
4486 S += " size_t Block_size;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004487 if (hasCopy) {
4488 S += " void (*copy)(struct ";
4489 S += ImplTag; S += "*, struct ";
4490 S += ImplTag; S += "*);\n";
4491
4492 S += " void (*dispose)(struct ";
4493 S += ImplTag; S += "*);\n";
4494 }
4495 S += "} ";
4496
4497 S += DescTag + "_DATA = { 0, sizeof(struct ";
4498 S += ImplTag + ")";
4499 if (hasCopy) {
4500 S += ", __" + FunName.str() + "_block_copy_" + utostr(i);
4501 S += ", __" + FunName.str() + "_block_dispose_" + utostr(i);
4502 }
4503 S += "};\n";
4504 return S;
4505}
4506
4507void RewriteModernObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
4508 StringRef FunName) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004509 bool RewriteSC = (GlobalVarDecl &&
4510 !Blocks.empty() &&
4511 GlobalVarDecl->getStorageClass() == SC_Static &&
4512 GlobalVarDecl->getType().getCVRQualifiers());
4513 if (RewriteSC) {
4514 std::string SC(" void __");
4515 SC += GlobalVarDecl->getNameAsString();
4516 SC += "() {}";
4517 InsertText(FunLocStart, SC);
4518 }
4519
4520 // Insert closures that were part of the function.
4521 for (unsigned i = 0, count=0; i < Blocks.size(); i++) {
4522 CollectBlockDeclRefInfo(Blocks[i]);
4523 // Need to copy-in the inner copied-in variables not actually used in this
4524 // block.
4525 for (int j = 0; j < InnerDeclRefsCount[i]; j++) {
John McCallf4b88a42012-03-10 09:33:50 +00004526 DeclRefExpr *Exp = InnerDeclRefs[count++];
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004527 ValueDecl *VD = Exp->getDecl();
4528 BlockDeclRefs.push_back(Exp);
John McCallf4b88a42012-03-10 09:33:50 +00004529 if (!VD->hasAttr<BlocksAttr>()) {
4530 if (!BlockByCopyDeclsPtrSet.count(VD)) {
4531 BlockByCopyDeclsPtrSet.insert(VD);
4532 BlockByCopyDecls.push_back(VD);
4533 }
4534 continue;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004535 }
John McCallf4b88a42012-03-10 09:33:50 +00004536
4537 if (!BlockByRefDeclsPtrSet.count(VD)) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004538 BlockByRefDeclsPtrSet.insert(VD);
4539 BlockByRefDecls.push_back(VD);
4540 }
John McCallf4b88a42012-03-10 09:33:50 +00004541
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004542 // imported objects in the inner blocks not used in the outer
4543 // blocks must be copied/disposed in the outer block as well.
John McCallf4b88a42012-03-10 09:33:50 +00004544 if (VD->getType()->isObjCObjectPointerType() ||
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004545 VD->getType()->isBlockPointerType())
4546 ImportedBlockDecls.insert(VD);
4547 }
4548
4549 std::string ImplTag = "__" + FunName.str() + "_block_impl_" + utostr(i);
4550 std::string DescTag = "__" + FunName.str() + "_block_desc_" + utostr(i);
4551
4552 std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
4553
4554 InsertText(FunLocStart, CI);
4555
4556 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
4557
4558 InsertText(FunLocStart, CF);
4559
4560 if (ImportedBlockDecls.size()) {
4561 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
4562 InsertText(FunLocStart, HF);
4563 }
4564 std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
4565 ImportedBlockDecls.size() > 0);
4566 InsertText(FunLocStart, BD);
4567
4568 BlockDeclRefs.clear();
4569 BlockByRefDecls.clear();
4570 BlockByRefDeclsPtrSet.clear();
4571 BlockByCopyDecls.clear();
4572 BlockByCopyDeclsPtrSet.clear();
4573 ImportedBlockDecls.clear();
4574 }
4575 if (RewriteSC) {
4576 // Must insert any 'const/volatile/static here. Since it has been
4577 // removed as result of rewriting of block literals.
4578 std::string SC;
4579 if (GlobalVarDecl->getStorageClass() == SC_Static)
4580 SC = "static ";
4581 if (GlobalVarDecl->getType().isConstQualified())
4582 SC += "const ";
4583 if (GlobalVarDecl->getType().isVolatileQualified())
4584 SC += "volatile ";
4585 if (GlobalVarDecl->getType().isRestrictQualified())
4586 SC += "restrict ";
4587 InsertText(FunLocStart, SC);
4588 }
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00004589 if (GlobalConstructionExp) {
4590 // extra fancy dance for global literal expression.
4591
4592 // Always the latest block expression on the block stack.
4593 std::string Tag = "__";
4594 Tag += FunName;
4595 Tag += "_block_impl_";
4596 Tag += utostr(Blocks.size()-1);
4597 std::string globalBuf = "static ";
4598 globalBuf += Tag; globalBuf += " ";
4599 std::string SStr;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004600
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00004601 llvm::raw_string_ostream constructorExprBuf(SStr);
Richard Smithd1420c62012-08-16 03:56:14 +00004602 GlobalConstructionExp->printPretty(constructorExprBuf, 0,
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00004603 PrintingPolicy(LangOpts));
4604 globalBuf += constructorExprBuf.str();
4605 globalBuf += ";\n";
4606 InsertText(FunLocStart, globalBuf);
4607 GlobalConstructionExp = 0;
4608 }
4609
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004610 Blocks.clear();
4611 InnerDeclRefsCount.clear();
4612 InnerDeclRefs.clear();
4613 RewrittenBlockExprs.clear();
4614}
4615
4616void RewriteModernObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
Fariborz Jahanian04189532012-04-25 17:56:48 +00004617 SourceLocation FunLocStart =
4618 (!Blocks.empty()) ? getFunctionSourceLocation(*this, FD)
4619 : FD->getTypeSpecStartLoc();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004620 StringRef FuncName = FD->getName();
4621
4622 SynthesizeBlockLiterals(FunLocStart, FuncName);
4623}
4624
4625static void BuildUniqueMethodName(std::string &Name,
4626 ObjCMethodDecl *MD) {
4627 ObjCInterfaceDecl *IFace = MD->getClassInterface();
4628 Name = IFace->getName();
4629 Name += "__" + MD->getSelector().getAsString();
4630 // Convert colons to underscores.
4631 std::string::size_type loc = 0;
4632 while ((loc = Name.find(":", loc)) != std::string::npos)
4633 Name.replace(loc, 1, "_");
4634}
4635
4636void RewriteModernObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
4637 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
4638 //SourceLocation FunLocStart = MD->getLocStart();
4639 SourceLocation FunLocStart = MD->getLocStart();
4640 std::string FuncName;
4641 BuildUniqueMethodName(FuncName, MD);
4642 SynthesizeBlockLiterals(FunLocStart, FuncName);
4643}
4644
4645void RewriteModernObjC::GetBlockDeclRefExprs(Stmt *S) {
4646 for (Stmt::child_range CI = S->children(); CI; ++CI)
4647 if (*CI) {
4648 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
4649 GetBlockDeclRefExprs(CBE->getBody());
4650 else
4651 GetBlockDeclRefExprs(*CI);
4652 }
4653 // Handle specific things.
Fariborz Jahanian0e976812012-04-16 23:00:57 +00004654 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4655 if (DRE->refersToEnclosingLocal()) {
4656 // FIXME: Handle enums.
4657 if (!isa<FunctionDecl>(DRE->getDecl()))
4658 BlockDeclRefs.push_back(DRE);
4659 if (HasLocalVariableExternalStorage(DRE->getDecl()))
4660 BlockDeclRefs.push_back(DRE);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004661 }
Fariborz Jahanian0e976812012-04-16 23:00:57 +00004662 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004663
4664 return;
4665}
4666
4667void RewriteModernObjC::GetInnerBlockDeclRefExprs(Stmt *S,
John McCallf4b88a42012-03-10 09:33:50 +00004668 SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004669 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts) {
4670 for (Stmt::child_range CI = S->children(); CI; ++CI)
4671 if (*CI) {
4672 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI)) {
4673 InnerContexts.insert(cast<DeclContext>(CBE->getBlockDecl()));
4674 GetInnerBlockDeclRefExprs(CBE->getBody(),
4675 InnerBlockDeclRefs,
4676 InnerContexts);
4677 }
4678 else
4679 GetInnerBlockDeclRefExprs(*CI,
4680 InnerBlockDeclRefs,
4681 InnerContexts);
4682
4683 }
4684 // Handle specific things.
John McCallf4b88a42012-03-10 09:33:50 +00004685 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4686 if (DRE->refersToEnclosingLocal()) {
4687 if (!isa<FunctionDecl>(DRE->getDecl()) &&
4688 !InnerContexts.count(DRE->getDecl()->getDeclContext()))
4689 InnerBlockDeclRefs.push_back(DRE);
4690 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl()))
4691 if (Var->isFunctionOrMethodVarDecl())
4692 ImportedLocalExternalDecls.insert(Var);
4693 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004694 }
4695
4696 return;
4697}
4698
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00004699/// convertObjCTypeToCStyleType - This routine converts such objc types
4700/// as qualified objects, and blocks to their closest c/c++ types that
4701/// it can. It returns true if input type was modified.
4702bool RewriteModernObjC::convertObjCTypeToCStyleType(QualType &T) {
4703 QualType oldT = T;
4704 convertBlockPointerToFunctionPointer(T);
4705 if (T->isFunctionPointerType()) {
4706 QualType PointeeTy;
4707 if (const PointerType* PT = T->getAs<PointerType>()) {
4708 PointeeTy = PT->getPointeeType();
4709 if (const FunctionType *FT = PointeeTy->getAs<FunctionType>()) {
4710 T = convertFunctionTypeOfBlocks(FT);
4711 T = Context->getPointerType(T);
4712 }
4713 }
4714 }
4715
4716 convertToUnqualifiedObjCType(T);
4717 return T != oldT;
4718}
4719
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004720/// convertFunctionTypeOfBlocks - This routine converts a function type
4721/// whose result type may be a block pointer or whose argument type(s)
4722/// might be block pointers to an equivalent function type replacing
4723/// all block pointers to function pointers.
4724QualType RewriteModernObjC::convertFunctionTypeOfBlocks(const FunctionType *FT) {
4725 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
4726 // FTP will be null for closures that don't take arguments.
4727 // Generate a funky cast.
4728 SmallVector<QualType, 8> ArgTypes;
4729 QualType Res = FT->getResultType();
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00004730 bool modified = convertObjCTypeToCStyleType(Res);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004731
4732 if (FTP) {
4733 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4734 E = FTP->arg_type_end(); I && (I != E); ++I) {
4735 QualType t = *I;
4736 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00004737 if (convertObjCTypeToCStyleType(t))
4738 modified = true;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004739 ArgTypes.push_back(t);
4740 }
4741 }
4742 QualType FuncType;
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00004743 if (modified)
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004744 FuncType = getSimpleFunctionType(Res, &ArgTypes[0], ArgTypes.size());
4745 else FuncType = QualType(FT, 0);
4746 return FuncType;
4747}
4748
4749Stmt *RewriteModernObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
4750 // Navigate to relevant type information.
4751 const BlockPointerType *CPT = 0;
4752
4753 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
4754 CPT = DRE->getType()->getAs<BlockPointerType>();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004755 } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
4756 CPT = MExpr->getType()->getAs<BlockPointerType>();
4757 }
4758 else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
4759 return SynthesizeBlockCall(Exp, PRE->getSubExpr());
4760 }
4761 else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
4762 CPT = IEXPR->getType()->getAs<BlockPointerType>();
4763 else if (const ConditionalOperator *CEXPR =
4764 dyn_cast<ConditionalOperator>(BlockExp)) {
4765 Expr *LHSExp = CEXPR->getLHS();
4766 Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
4767 Expr *RHSExp = CEXPR->getRHS();
4768 Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
4769 Expr *CONDExp = CEXPR->getCond();
4770 ConditionalOperator *CondExpr =
4771 new (Context) ConditionalOperator(CONDExp,
4772 SourceLocation(), cast<Expr>(LHSStmt),
4773 SourceLocation(), cast<Expr>(RHSStmt),
4774 Exp->getType(), VK_RValue, OK_Ordinary);
4775 return CondExpr;
4776 } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
4777 CPT = IRE->getType()->getAs<BlockPointerType>();
4778 } else if (const PseudoObjectExpr *POE
4779 = dyn_cast<PseudoObjectExpr>(BlockExp)) {
4780 CPT = POE->getType()->castAs<BlockPointerType>();
4781 } else {
4782 assert(1 && "RewriteBlockClass: Bad type");
4783 }
4784 assert(CPT && "RewriteBlockClass: Bad type");
4785 const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
4786 assert(FT && "RewriteBlockClass: Bad type");
4787 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
4788 // FTP will be null for closures that don't take arguments.
4789
4790 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
4791 SourceLocation(), SourceLocation(),
4792 &Context->Idents.get("__block_impl"));
4793 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
4794
4795 // Generate a funky cast.
4796 SmallVector<QualType, 8> ArgTypes;
4797
4798 // Push the block argument type.
4799 ArgTypes.push_back(PtrBlock);
4800 if (FTP) {
4801 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4802 E = FTP->arg_type_end(); I && (I != E); ++I) {
4803 QualType t = *I;
4804 // Make sure we convert "t (^)(...)" to "t (*)(...)".
4805 if (!convertBlockPointerToFunctionPointer(t))
4806 convertToUnqualifiedObjCType(t);
4807 ArgTypes.push_back(t);
4808 }
4809 }
4810 // Now do the pointer to function cast.
4811 QualType PtrToFuncCastType
4812 = getSimpleFunctionType(Exp->getType(), &ArgTypes[0], ArgTypes.size());
4813
4814 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
4815
4816 CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
4817 CK_BitCast,
4818 const_cast<Expr*>(BlockExp));
4819 // Don't forget the parens to enforce the proper binding.
4820 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4821 BlkCast);
4822 //PE->dump();
4823
4824 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4825 SourceLocation(),
4826 &Context->Idents.get("FuncPtr"),
4827 Context->VoidPtrTy, 0,
4828 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smithca523302012-06-10 03:12:00 +00004829 ICIS_NoInit);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004830 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
4831 FD->getType(), VK_LValue,
4832 OK_Ordinary);
4833
4834
4835 CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
4836 CK_BitCast, ME);
4837 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
4838
4839 SmallVector<Expr*, 8> BlkExprs;
4840 // Add the implicit argument.
4841 BlkExprs.push_back(BlkCast);
4842 // Add the user arguments.
4843 for (CallExpr::arg_iterator I = Exp->arg_begin(),
4844 E = Exp->arg_end(); I != E; ++I) {
4845 BlkExprs.push_back(*I);
4846 }
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00004847 CallExpr *CE = new (Context) CallExpr(*Context, PE, BlkExprs,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004848 Exp->getType(), VK_RValue,
4849 SourceLocation());
4850 return CE;
4851}
4852
4853// We need to return the rewritten expression to handle cases where the
John McCallf4b88a42012-03-10 09:33:50 +00004854// DeclRefExpr is embedded in another expression being rewritten.
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004855// For example:
4856//
4857// int main() {
4858// __block Foo *f;
4859// __block int i;
4860//
4861// void (^myblock)() = ^() {
John McCallf4b88a42012-03-10 09:33:50 +00004862// [f test]; // f is a DeclRefExpr embedded in a message (which is being rewritten).
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004863// i = 77;
4864// };
4865//}
John McCallf4b88a42012-03-10 09:33:50 +00004866Stmt *RewriteModernObjC::RewriteBlockDeclRefExpr(DeclRefExpr *DeclRefExp) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004867 // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
4868 // for each DeclRefExp where BYREFVAR is name of the variable.
John McCallf4b88a42012-03-10 09:33:50 +00004869 ValueDecl *VD = DeclRefExp->getDecl();
4870 bool isArrow = DeclRefExp->refersToEnclosingLocal();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004871
4872 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4873 SourceLocation(),
4874 &Context->Idents.get("__forwarding"),
4875 Context->VoidPtrTy, 0,
4876 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smithca523302012-06-10 03:12:00 +00004877 ICIS_NoInit);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004878 MemberExpr *ME = new (Context) MemberExpr(DeclRefExp, isArrow,
4879 FD, SourceLocation(),
4880 FD->getType(), VK_LValue,
4881 OK_Ordinary);
4882
4883 StringRef Name = VD->getName();
4884 FD = FieldDecl::Create(*Context, 0, SourceLocation(), SourceLocation(),
4885 &Context->Idents.get(Name),
4886 Context->VoidPtrTy, 0,
4887 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smithca523302012-06-10 03:12:00 +00004888 ICIS_NoInit);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004889 ME = new (Context) MemberExpr(ME, true, FD, SourceLocation(),
4890 DeclRefExp->getType(), VK_LValue, OK_Ordinary);
4891
4892
4893
4894 // Need parens to enforce precedence.
4895 ParenExpr *PE = new (Context) ParenExpr(DeclRefExp->getExprLoc(),
4896 DeclRefExp->getExprLoc(),
4897 ME);
4898 ReplaceStmt(DeclRefExp, PE);
4899 return PE;
4900}
4901
4902// Rewrites the imported local variable V with external storage
4903// (static, extern, etc.) as *V
4904//
4905Stmt *RewriteModernObjC::RewriteLocalVariableExternalStorage(DeclRefExpr *DRE) {
4906 ValueDecl *VD = DRE->getDecl();
4907 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4908 if (!ImportedLocalExternalDecls.count(Var))
4909 return DRE;
4910 Expr *Exp = new (Context) UnaryOperator(DRE, UO_Deref, DRE->getType(),
4911 VK_LValue, OK_Ordinary,
4912 DRE->getLocation());
4913 // Need parens to enforce precedence.
4914 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4915 Exp);
4916 ReplaceStmt(DRE, PE);
4917 return PE;
4918}
4919
4920void RewriteModernObjC::RewriteCastExpr(CStyleCastExpr *CE) {
4921 SourceLocation LocStart = CE->getLParenLoc();
4922 SourceLocation LocEnd = CE->getRParenLoc();
4923
4924 // Need to avoid trying to rewrite synthesized casts.
4925 if (LocStart.isInvalid())
4926 return;
4927 // Need to avoid trying to rewrite casts contained in macros.
4928 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
4929 return;
4930
4931 const char *startBuf = SM->getCharacterData(LocStart);
4932 const char *endBuf = SM->getCharacterData(LocEnd);
4933 QualType QT = CE->getType();
4934 const Type* TypePtr = QT->getAs<Type>();
4935 if (isa<TypeOfExprType>(TypePtr)) {
4936 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
4937 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
4938 std::string TypeAsString = "(";
4939 RewriteBlockPointerType(TypeAsString, QT);
4940 TypeAsString += ")";
4941 ReplaceText(LocStart, endBuf-startBuf+1, TypeAsString);
4942 return;
4943 }
4944 // advance the location to startArgList.
4945 const char *argPtr = startBuf;
4946
4947 while (*argPtr++ && (argPtr < endBuf)) {
4948 switch (*argPtr) {
4949 case '^':
4950 // Replace the '^' with '*'.
4951 LocStart = LocStart.getLocWithOffset(argPtr-startBuf);
4952 ReplaceText(LocStart, 1, "*");
4953 break;
4954 }
4955 }
4956 return;
4957}
4958
Fariborz Jahanianf1ee6872012-04-10 00:08:18 +00004959void RewriteModernObjC::RewriteImplicitCastObjCExpr(CastExpr *IC) {
4960 CastKind CastKind = IC->getCastKind();
Fariborz Jahanian43aa1c32012-04-16 22:14:01 +00004961 if (CastKind != CK_BlockPointerToObjCPointerCast &&
4962 CastKind != CK_AnyPointerToBlockPointerCast)
4963 return;
Fariborz Jahanianf1ee6872012-04-10 00:08:18 +00004964
Fariborz Jahanian43aa1c32012-04-16 22:14:01 +00004965 QualType QT = IC->getType();
4966 (void)convertBlockPointerToFunctionPointer(QT);
4967 std::string TypeString(QT.getAsString(Context->getPrintingPolicy()));
4968 std::string Str = "(";
4969 Str += TypeString;
4970 Str += ")";
4971 InsertText(IC->getSubExpr()->getLocStart(), &Str[0], Str.size());
4972
Fariborz Jahanianf1ee6872012-04-10 00:08:18 +00004973 return;
4974}
4975
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004976void RewriteModernObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
4977 SourceLocation DeclLoc = FD->getLocation();
4978 unsigned parenCount = 0;
4979
4980 // We have 1 or more arguments that have closure pointers.
4981 const char *startBuf = SM->getCharacterData(DeclLoc);
4982 const char *startArgList = strchr(startBuf, '(');
4983
4984 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
4985
4986 parenCount++;
4987 // advance the location to startArgList.
4988 DeclLoc = DeclLoc.getLocWithOffset(startArgList-startBuf);
4989 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
4990
4991 const char *argPtr = startArgList;
4992
4993 while (*argPtr++ && parenCount) {
4994 switch (*argPtr) {
4995 case '^':
4996 // Replace the '^' with '*'.
4997 DeclLoc = DeclLoc.getLocWithOffset(argPtr-startArgList);
4998 ReplaceText(DeclLoc, 1, "*");
4999 break;
5000 case '(':
5001 parenCount++;
5002 break;
5003 case ')':
5004 parenCount--;
5005 break;
5006 }
5007 }
5008 return;
5009}
5010
5011bool RewriteModernObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
5012 const FunctionProtoType *FTP;
5013 const PointerType *PT = QT->getAs<PointerType>();
5014 if (PT) {
5015 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
5016 } else {
5017 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
5018 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
5019 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
5020 }
5021 if (FTP) {
5022 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
5023 E = FTP->arg_type_end(); I != E; ++I)
5024 if (isTopLevelBlockPointerType(*I))
5025 return true;
5026 }
5027 return false;
5028}
5029
5030bool RewriteModernObjC::PointerTypeTakesAnyObjCQualifiedType(QualType QT) {
5031 const FunctionProtoType *FTP;
5032 const PointerType *PT = QT->getAs<PointerType>();
5033 if (PT) {
5034 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
5035 } else {
5036 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
5037 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
5038 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
5039 }
5040 if (FTP) {
5041 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
5042 E = FTP->arg_type_end(); I != E; ++I) {
5043 if ((*I)->isObjCQualifiedIdType())
5044 return true;
5045 if ((*I)->isObjCObjectPointerType() &&
5046 (*I)->getPointeeType()->isObjCQualifiedInterfaceType())
5047 return true;
5048 }
5049
5050 }
5051 return false;
5052}
5053
5054void RewriteModernObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
5055 const char *&RParen) {
5056 const char *argPtr = strchr(Name, '(');
5057 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
5058
5059 LParen = argPtr; // output the start.
5060 argPtr++; // skip past the left paren.
5061 unsigned parenCount = 1;
5062
5063 while (*argPtr && parenCount) {
5064 switch (*argPtr) {
5065 case '(': parenCount++; break;
5066 case ')': parenCount--; break;
5067 default: break;
5068 }
5069 if (parenCount) argPtr++;
5070 }
5071 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
5072 RParen = argPtr; // output the end
5073}
5074
5075void RewriteModernObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
5076 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
5077 RewriteBlockPointerFunctionArgs(FD);
5078 return;
5079 }
5080 // Handle Variables and Typedefs.
5081 SourceLocation DeclLoc = ND->getLocation();
5082 QualType DeclT;
5083 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
5084 DeclT = VD->getType();
5085 else if (TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(ND))
5086 DeclT = TDD->getUnderlyingType();
5087 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
5088 DeclT = FD->getType();
5089 else
5090 llvm_unreachable("RewriteBlockPointerDecl(): Decl type not yet handled");
5091
5092 const char *startBuf = SM->getCharacterData(DeclLoc);
5093 const char *endBuf = startBuf;
5094 // scan backward (from the decl location) for the end of the previous decl.
5095 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
5096 startBuf--;
5097 SourceLocation Start = DeclLoc.getLocWithOffset(startBuf-endBuf);
5098 std::string buf;
5099 unsigned OrigLength=0;
5100 // *startBuf != '^' if we are dealing with a pointer to function that
5101 // may take block argument types (which will be handled below).
5102 if (*startBuf == '^') {
5103 // Replace the '^' with '*', computing a negative offset.
5104 buf = '*';
5105 startBuf++;
5106 OrigLength++;
5107 }
5108 while (*startBuf != ')') {
5109 buf += *startBuf;
5110 startBuf++;
5111 OrigLength++;
5112 }
5113 buf += ')';
5114 OrigLength++;
5115
5116 if (PointerTypeTakesAnyBlockArguments(DeclT) ||
5117 PointerTypeTakesAnyObjCQualifiedType(DeclT)) {
5118 // Replace the '^' with '*' for arguments.
5119 // Replace id<P> with id/*<>*/
5120 DeclLoc = ND->getLocation();
5121 startBuf = SM->getCharacterData(DeclLoc);
5122 const char *argListBegin, *argListEnd;
5123 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
5124 while (argListBegin < argListEnd) {
5125 if (*argListBegin == '^')
5126 buf += '*';
5127 else if (*argListBegin == '<') {
5128 buf += "/*";
5129 buf += *argListBegin++;
Dmitri Gribenko1ad23d62012-09-10 21:20:09 +00005130 OrigLength++;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005131 while (*argListBegin != '>') {
5132 buf += *argListBegin++;
5133 OrigLength++;
5134 }
5135 buf += *argListBegin;
5136 buf += "*/";
5137 }
5138 else
5139 buf += *argListBegin;
5140 argListBegin++;
5141 OrigLength++;
5142 }
5143 buf += ')';
5144 OrigLength++;
5145 }
5146 ReplaceText(Start, OrigLength, buf);
5147
5148 return;
5149}
5150
5151
5152/// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
5153/// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
5154/// struct Block_byref_id_object *src) {
5155/// _Block_object_assign (&_dest->object, _src->object,
5156/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
5157/// [|BLOCK_FIELD_IS_WEAK]) // object
5158/// _Block_object_assign(&_dest->object, _src->object,
5159/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
5160/// [|BLOCK_FIELD_IS_WEAK]) // block
5161/// }
5162/// And:
5163/// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
5164/// _Block_object_dispose(_src->object,
5165/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
5166/// [|BLOCK_FIELD_IS_WEAK]) // object
5167/// _Block_object_dispose(_src->object,
5168/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
5169/// [|BLOCK_FIELD_IS_WEAK]) // block
5170/// }
5171
5172std::string RewriteModernObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
5173 int flag) {
5174 std::string S;
5175 if (CopyDestroyCache.count(flag))
5176 return S;
5177 CopyDestroyCache.insert(flag);
5178 S = "static void __Block_byref_id_object_copy_";
5179 S += utostr(flag);
5180 S += "(void *dst, void *src) {\n";
5181
5182 // offset into the object pointer is computed as:
5183 // void * + void* + int + int + void* + void *
5184 unsigned IntSize =
5185 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
5186 unsigned VoidPtrSize =
5187 static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
5188
5189 unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/Context->getCharWidth();
5190 S += " _Block_object_assign((char*)dst + ";
5191 S += utostr(offset);
5192 S += ", *(void * *) ((char*)src + ";
5193 S += utostr(offset);
5194 S += "), ";
5195 S += utostr(flag);
5196 S += ");\n}\n";
5197
5198 S += "static void __Block_byref_id_object_dispose_";
5199 S += utostr(flag);
5200 S += "(void *src) {\n";
5201 S += " _Block_object_dispose(*(void * *) ((char*)src + ";
5202 S += utostr(offset);
5203 S += "), ";
5204 S += utostr(flag);
5205 S += ");\n}\n";
5206 return S;
5207}
5208
5209/// RewriteByRefVar - For each __block typex ND variable this routine transforms
5210/// the declaration into:
5211/// struct __Block_byref_ND {
5212/// void *__isa; // NULL for everything except __weak pointers
5213/// struct __Block_byref_ND *__forwarding;
5214/// int32_t __flags;
5215/// int32_t __size;
5216/// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
5217/// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
5218/// typex ND;
5219/// };
5220///
5221/// It then replaces declaration of ND variable with:
5222/// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
5223/// __size=sizeof(struct __Block_byref_ND),
5224/// ND=initializer-if-any};
5225///
5226///
Fariborz Jahanian4fe261c2012-04-24 19:38:45 +00005227void RewriteModernObjC::RewriteByRefVar(VarDecl *ND, bool firstDecl,
5228 bool lastDecl) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005229 int flag = 0;
5230 int isa = 0;
5231 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
5232 if (DeclLoc.isInvalid())
5233 // If type location is missing, it is because of missing type (a warning).
5234 // Use variable's location which is good for this case.
5235 DeclLoc = ND->getLocation();
5236 const char *startBuf = SM->getCharacterData(DeclLoc);
5237 SourceLocation X = ND->getLocEnd();
5238 X = SM->getExpansionLoc(X);
5239 const char *endBuf = SM->getCharacterData(X);
5240 std::string Name(ND->getNameAsString());
5241 std::string ByrefType;
5242 RewriteByRefString(ByrefType, Name, ND, true);
5243 ByrefType += " {\n";
5244 ByrefType += " void *__isa;\n";
5245 RewriteByRefString(ByrefType, Name, ND);
5246 ByrefType += " *__forwarding;\n";
5247 ByrefType += " int __flags;\n";
5248 ByrefType += " int __size;\n";
5249 // Add void *__Block_byref_id_object_copy;
5250 // void *__Block_byref_id_object_dispose; if needed.
5251 QualType Ty = ND->getType();
Fariborz Jahanianb15c8982012-11-28 23:12:17 +00005252 bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty, ND);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005253 if (HasCopyAndDispose) {
5254 ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
5255 ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
5256 }
5257
5258 QualType T = Ty;
5259 (void)convertBlockPointerToFunctionPointer(T);
5260 T.getAsStringInternal(Name, Context->getPrintingPolicy());
5261
5262 ByrefType += " " + Name + ";\n";
5263 ByrefType += "};\n";
5264 // Insert this type in global scope. It is needed by helper function.
5265 SourceLocation FunLocStart;
5266 if (CurFunctionDef)
Fariborz Jahanianb75f8de2012-04-19 00:50:01 +00005267 FunLocStart = getFunctionSourceLocation(*this, CurFunctionDef);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005268 else {
5269 assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null");
5270 FunLocStart = CurMethodDef->getLocStart();
5271 }
5272 InsertText(FunLocStart, ByrefType);
Fariborz Jahanian8247c4e2012-04-24 16:45:27 +00005273
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005274 if (Ty.isObjCGCWeak()) {
5275 flag |= BLOCK_FIELD_IS_WEAK;
5276 isa = 1;
5277 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005278 if (HasCopyAndDispose) {
5279 flag = BLOCK_BYREF_CALLER;
5280 QualType Ty = ND->getType();
5281 // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
5282 if (Ty->isBlockPointerType())
5283 flag |= BLOCK_FIELD_IS_BLOCK;
5284 else
5285 flag |= BLOCK_FIELD_IS_OBJECT;
5286 std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
5287 if (!HF.empty())
Fariborz Jahanian31c4a4b2013-02-07 22:50:40 +00005288 Preamble += HF;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005289 }
5290
5291 // struct __Block_byref_ND ND =
5292 // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
5293 // initializer-if-any};
5294 bool hasInit = (ND->getInit() != 0);
Fariborz Jahanian104dbf92012-04-11 23:57:12 +00005295 // FIXME. rewriter does not support __block c++ objects which
5296 // require construction.
Fariborz Jahanian65a7c682012-04-26 23:20:25 +00005297 if (hasInit)
5298 if (CXXConstructExpr *CExp = dyn_cast<CXXConstructExpr>(ND->getInit())) {
5299 CXXConstructorDecl *CXXDecl = CExp->getConstructor();
5300 if (CXXDecl && CXXDecl->isDefaultConstructor())
5301 hasInit = false;
5302 }
5303
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005304 unsigned flags = 0;
5305 if (HasCopyAndDispose)
5306 flags |= BLOCK_HAS_COPY_DISPOSE;
5307 Name = ND->getNameAsString();
5308 ByrefType.clear();
5309 RewriteByRefString(ByrefType, Name, ND);
5310 std::string ForwardingCastType("(");
5311 ForwardingCastType += ByrefType + " *)";
Fariborz Jahanian8247c4e2012-04-24 16:45:27 +00005312 ByrefType += " " + Name + " = {(void*)";
5313 ByrefType += utostr(isa);
5314 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
5315 ByrefType += utostr(flags);
5316 ByrefType += ", ";
5317 ByrefType += "sizeof(";
5318 RewriteByRefString(ByrefType, Name, ND);
5319 ByrefType += ")";
5320 if (HasCopyAndDispose) {
5321 ByrefType += ", __Block_byref_id_object_copy_";
5322 ByrefType += utostr(flag);
5323 ByrefType += ", __Block_byref_id_object_dispose_";
5324 ByrefType += utostr(flag);
5325 }
5326
Fariborz Jahanian4fe261c2012-04-24 19:38:45 +00005327 if (!firstDecl) {
5328 // In multiple __block declarations, and for all but 1st declaration,
5329 // find location of the separating comma. This would be start location
5330 // where new text is to be inserted.
5331 DeclLoc = ND->getLocation();
5332 const char *startDeclBuf = SM->getCharacterData(DeclLoc);
5333 const char *commaBuf = startDeclBuf;
5334 while (*commaBuf != ',')
5335 commaBuf--;
5336 assert((*commaBuf == ',') && "RewriteByRefVar: can't find ','");
5337 DeclLoc = DeclLoc.getLocWithOffset(commaBuf - startDeclBuf);
5338 startBuf = commaBuf;
5339 }
5340
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005341 if (!hasInit) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005342 ByrefType += "};\n";
5343 unsigned nameSize = Name.size();
5344 // for block or function pointer declaration. Name is aleady
5345 // part of the declaration.
5346 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType())
5347 nameSize = 1;
5348 ReplaceText(DeclLoc, endBuf-startBuf+nameSize, ByrefType);
5349 }
5350 else {
Fariborz Jahanian8247c4e2012-04-24 16:45:27 +00005351 ByrefType += ", ";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005352 SourceLocation startLoc;
5353 Expr *E = ND->getInit();
5354 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
5355 startLoc = ECE->getLParenLoc();
5356 else
5357 startLoc = E->getLocStart();
5358 startLoc = SM->getExpansionLoc(startLoc);
5359 endBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005360 ReplaceText(DeclLoc, endBuf-startBuf, ByrefType);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005361
Fariborz Jahanian4fe261c2012-04-24 19:38:45 +00005362 const char separator = lastDecl ? ';' : ',';
5363 const char *startInitializerBuf = SM->getCharacterData(startLoc);
5364 const char *separatorBuf = strchr(startInitializerBuf, separator);
5365 assert((*separatorBuf == separator) &&
5366 "RewriteByRefVar: can't find ';' or ','");
5367 SourceLocation separatorLoc =
5368 startLoc.getLocWithOffset(separatorBuf-startInitializerBuf);
5369
5370 InsertText(separatorLoc, lastDecl ? "}" : "};\n");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005371 }
5372 return;
5373}
5374
5375void RewriteModernObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
5376 // Add initializers for any closure decl refs.
5377 GetBlockDeclRefExprs(Exp->getBody());
5378 if (BlockDeclRefs.size()) {
5379 // Unique all "by copy" declarations.
5380 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00005381 if (!BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005382 if (!BlockByCopyDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5383 BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5384 BlockByCopyDecls.push_back(BlockDeclRefs[i]->getDecl());
5385 }
5386 }
5387 // Unique all "by ref" declarations.
5388 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00005389 if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005390 if (!BlockByRefDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5391 BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5392 BlockByRefDecls.push_back(BlockDeclRefs[i]->getDecl());
5393 }
5394 }
5395 // Find any imported blocks...they will need special attention.
5396 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00005397 if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005398 BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
5399 BlockDeclRefs[i]->getType()->isBlockPointerType())
5400 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
5401 }
5402}
5403
5404FunctionDecl *RewriteModernObjC::SynthBlockInitFunctionDecl(StringRef name) {
5405 IdentifierInfo *ID = &Context->Idents.get(name);
5406 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
5407 return FunctionDecl::Create(*Context, TUDecl, SourceLocation(),
5408 SourceLocation(), ID, FType, 0, SC_Extern,
5409 SC_None, false, false);
5410}
5411
5412Stmt *RewriteModernObjC::SynthBlockInitExpr(BlockExpr *Exp,
John McCallf4b88a42012-03-10 09:33:50 +00005413 const SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs) {
Fariborz Jahaniand13c2c22012-03-22 19:54:39 +00005414
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005415 const BlockDecl *block = Exp->getBlockDecl();
Fariborz Jahaniand13c2c22012-03-22 19:54:39 +00005416
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005417 Blocks.push_back(Exp);
5418
5419 CollectBlockDeclRefInfo(Exp);
5420
5421 // Add inner imported variables now used in current block.
5422 int countOfInnerDecls = 0;
5423 if (!InnerBlockDeclRefs.empty()) {
5424 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++) {
John McCallf4b88a42012-03-10 09:33:50 +00005425 DeclRefExpr *Exp = InnerBlockDeclRefs[i];
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005426 ValueDecl *VD = Exp->getDecl();
John McCallf4b88a42012-03-10 09:33:50 +00005427 if (!VD->hasAttr<BlocksAttr>() && !BlockByCopyDeclsPtrSet.count(VD)) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005428 // We need to save the copied-in variables in nested
5429 // blocks because it is needed at the end for some of the API generations.
5430 // See SynthesizeBlockLiterals routine.
5431 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5432 BlockDeclRefs.push_back(Exp);
5433 BlockByCopyDeclsPtrSet.insert(VD);
5434 BlockByCopyDecls.push_back(VD);
5435 }
John McCallf4b88a42012-03-10 09:33:50 +00005436 if (VD->hasAttr<BlocksAttr>() && !BlockByRefDeclsPtrSet.count(VD)) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005437 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5438 BlockDeclRefs.push_back(Exp);
5439 BlockByRefDeclsPtrSet.insert(VD);
5440 BlockByRefDecls.push_back(VD);
5441 }
5442 }
5443 // Find any imported blocks...they will need special attention.
5444 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00005445 if (InnerBlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005446 InnerBlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
5447 InnerBlockDeclRefs[i]->getType()->isBlockPointerType())
5448 ImportedBlockDecls.insert(InnerBlockDeclRefs[i]->getDecl());
5449 }
5450 InnerDeclRefsCount.push_back(countOfInnerDecls);
5451
5452 std::string FuncName;
5453
5454 if (CurFunctionDef)
5455 FuncName = CurFunctionDef->getNameAsString();
5456 else if (CurMethodDef)
5457 BuildUniqueMethodName(FuncName, CurMethodDef);
5458 else if (GlobalVarDecl)
5459 FuncName = std::string(GlobalVarDecl->getNameAsString());
5460
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00005461 bool GlobalBlockExpr =
5462 block->getDeclContext()->getRedeclContext()->isFileContext();
5463
5464 if (GlobalBlockExpr && !GlobalVarDecl) {
5465 Diags.Report(block->getLocation(), GlobalBlockRewriteFailedDiag);
5466 GlobalBlockExpr = false;
5467 }
5468
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005469 std::string BlockNumber = utostr(Blocks.size()-1);
5470
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005471 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
5472
5473 // Get a pointer to the function type so we can cast appropriately.
5474 QualType BFT = convertFunctionTypeOfBlocks(Exp->getFunctionType());
5475 QualType FType = Context->getPointerType(BFT);
5476
5477 FunctionDecl *FD;
5478 Expr *NewRep;
5479
5480 // Simulate a contructor call...
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00005481 std::string Tag;
5482
5483 if (GlobalBlockExpr)
5484 Tag = "__global_";
5485 else
5486 Tag = "__";
5487 Tag += FuncName + "_block_impl_" + BlockNumber;
5488
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005489 FD = SynthBlockInitFunctionDecl(Tag);
John McCallf4b88a42012-03-10 09:33:50 +00005490 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, false, FType, VK_RValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005491 SourceLocation());
5492
5493 SmallVector<Expr*, 4> InitExprs;
5494
5495 // Initialize the block function.
5496 FD = SynthBlockInitFunctionDecl(Func);
John McCallf4b88a42012-03-10 09:33:50 +00005497 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, false, FD->getType(),
5498 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005499 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
5500 CK_BitCast, Arg);
5501 InitExprs.push_back(castExpr);
5502
5503 // Initialize the block descriptor.
5504 std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
5505
5506 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl,
5507 SourceLocation(), SourceLocation(),
5508 &Context->Idents.get(DescData.c_str()),
5509 Context->VoidPtrTy, 0,
5510 SC_Static, SC_None);
5511 UnaryOperator *DescRefExpr =
John McCallf4b88a42012-03-10 09:33:50 +00005512 new (Context) UnaryOperator(new (Context) DeclRefExpr(NewVD, false,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005513 Context->VoidPtrTy,
5514 VK_LValue,
5515 SourceLocation()),
5516 UO_AddrOf,
5517 Context->getPointerType(Context->VoidPtrTy),
5518 VK_RValue, OK_Ordinary,
5519 SourceLocation());
5520 InitExprs.push_back(DescRefExpr);
5521
5522 // Add initializers for any closure decl refs.
5523 if (BlockDeclRefs.size()) {
5524 Expr *Exp;
5525 // Output all "by copy" declarations.
5526 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
5527 E = BlockByCopyDecls.end(); I != E; ++I) {
5528 if (isObjCType((*I)->getType())) {
5529 // FIXME: Conform to ABI ([[obj retain] autorelease]).
5530 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00005531 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(),
5532 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005533 if (HasLocalVariableExternalStorage(*I)) {
5534 QualType QT = (*I)->getType();
5535 QT = Context->getPointerType(QT);
5536 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
5537 OK_Ordinary, SourceLocation());
5538 }
5539 } else if (isTopLevelBlockPointerType((*I)->getType())) {
5540 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00005541 Arg = new (Context) DeclRefExpr(FD, false, FD->getType(),
5542 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005543 Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
5544 CK_BitCast, Arg);
5545 } else {
5546 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00005547 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(),
5548 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005549 if (HasLocalVariableExternalStorage(*I)) {
5550 QualType QT = (*I)->getType();
5551 QT = Context->getPointerType(QT);
5552 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
5553 OK_Ordinary, SourceLocation());
5554 }
5555
5556 }
5557 InitExprs.push_back(Exp);
5558 }
5559 // Output all "by ref" declarations.
5560 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
5561 E = BlockByRefDecls.end(); I != E; ++I) {
5562 ValueDecl *ND = (*I);
5563 std::string Name(ND->getNameAsString());
5564 std::string RecName;
5565 RewriteByRefString(RecName, Name, ND, true);
5566 IdentifierInfo *II = &Context->Idents.get(RecName.c_str()
5567 + sizeof("struct"));
5568 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
5569 SourceLocation(), SourceLocation(),
5570 II);
5571 assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl");
5572 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
5573
5574 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00005575 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(), VK_LValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005576 SourceLocation());
5577 bool isNestedCapturedVar = false;
5578 if (block)
5579 for (BlockDecl::capture_const_iterator ci = block->capture_begin(),
5580 ce = block->capture_end(); ci != ce; ++ci) {
5581 const VarDecl *variable = ci->getVariable();
5582 if (variable == ND && ci->isNested()) {
5583 assert (ci->isByRef() &&
5584 "SynthBlockInitExpr - captured block variable is not byref");
5585 isNestedCapturedVar = true;
5586 break;
5587 }
5588 }
5589 // captured nested byref variable has its address passed. Do not take
5590 // its address again.
5591 if (!isNestedCapturedVar)
5592 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf,
5593 Context->getPointerType(Exp->getType()),
5594 VK_RValue, OK_Ordinary, SourceLocation());
5595 Exp = NoTypeInfoCStyleCastExpr(Context, castT, CK_BitCast, Exp);
5596 InitExprs.push_back(Exp);
5597 }
5598 }
5599 if (ImportedBlockDecls.size()) {
5600 // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
5601 int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
5602 unsigned IntSize =
5603 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
5604 Expr *FlagExp = IntegerLiteral::Create(*Context, llvm::APInt(IntSize, flag),
5605 Context->IntTy, SourceLocation());
5606 InitExprs.push_back(FlagExp);
5607 }
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00005608 NewRep = new (Context) CallExpr(*Context, DRE, InitExprs,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005609 FType, VK_LValue, SourceLocation());
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00005610
5611 if (GlobalBlockExpr) {
5612 assert (GlobalConstructionExp == 0 &&
5613 "SynthBlockInitExpr - GlobalConstructionExp must be null");
5614 GlobalConstructionExp = NewRep;
5615 NewRep = DRE;
5616 }
5617
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005618 NewRep = new (Context) UnaryOperator(NewRep, UO_AddrOf,
5619 Context->getPointerType(NewRep->getType()),
5620 VK_RValue, OK_Ordinary, SourceLocation());
5621 NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CK_BitCast,
5622 NewRep);
5623 BlockDeclRefs.clear();
5624 BlockByRefDecls.clear();
5625 BlockByRefDeclsPtrSet.clear();
5626 BlockByCopyDecls.clear();
5627 BlockByCopyDeclsPtrSet.clear();
5628 ImportedBlockDecls.clear();
5629 return NewRep;
5630}
5631
5632bool RewriteModernObjC::IsDeclStmtInForeachHeader(DeclStmt *DS) {
5633 if (const ObjCForCollectionStmt * CS =
5634 dyn_cast<ObjCForCollectionStmt>(Stmts.back()))
5635 return CS->getElement() == DS;
5636 return false;
5637}
5638
5639//===----------------------------------------------------------------------===//
5640// Function Body / Expression rewriting
5641//===----------------------------------------------------------------------===//
5642
5643Stmt *RewriteModernObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
5644 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
5645 isa<DoStmt>(S) || isa<ForStmt>(S))
5646 Stmts.push_back(S);
5647 else if (isa<ObjCForCollectionStmt>(S)) {
5648 Stmts.push_back(S);
5649 ObjCBcLabelNo.push_back(++BcLabelCount);
5650 }
5651
5652 // Pseudo-object operations and ivar references need special
5653 // treatment because we're going to recursively rewrite them.
5654 if (PseudoObjectExpr *PseudoOp = dyn_cast<PseudoObjectExpr>(S)) {
5655 if (isa<BinaryOperator>(PseudoOp->getSyntacticForm())) {
5656 return RewritePropertyOrImplicitSetter(PseudoOp);
5657 } else {
5658 return RewritePropertyOrImplicitGetter(PseudoOp);
5659 }
5660 } else if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
5661 return RewriteObjCIvarRefExpr(IvarRefExpr);
5662 }
Fariborz Jahanian9ffd1ae2013-02-08 18:57:50 +00005663 else if (isa<OpaqueValueExpr>(S))
5664 S = cast<OpaqueValueExpr>(S)->getSourceExpr();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005665
5666 SourceRange OrigStmtRange = S->getSourceRange();
5667
5668 // Perform a bottom up rewrite of all children.
5669 for (Stmt::child_range CI = S->children(); CI; ++CI)
5670 if (*CI) {
5671 Stmt *childStmt = (*CI);
5672 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(childStmt);
5673 if (newStmt) {
5674 *CI = newStmt;
5675 }
5676 }
5677
5678 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
John McCallf4b88a42012-03-10 09:33:50 +00005679 SmallVector<DeclRefExpr *, 8> InnerBlockDeclRefs;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005680 llvm::SmallPtrSet<const DeclContext *, 8> InnerContexts;
5681 InnerContexts.insert(BE->getBlockDecl());
5682 ImportedLocalExternalDecls.clear();
5683 GetInnerBlockDeclRefExprs(BE->getBody(),
5684 InnerBlockDeclRefs, InnerContexts);
5685 // Rewrite the block body in place.
5686 Stmt *SaveCurrentBody = CurrentBody;
5687 CurrentBody = BE->getBody();
5688 PropParentMap = 0;
5689 // block literal on rhs of a property-dot-sytax assignment
5690 // must be replaced by its synthesize ast so getRewrittenText
5691 // works as expected. In this case, what actually ends up on RHS
5692 // is the blockTranscribed which is the helper function for the
5693 // block literal; as in: self.c = ^() {[ace ARR];};
5694 bool saveDisableReplaceStmt = DisableReplaceStmt;
5695 DisableReplaceStmt = false;
5696 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
5697 DisableReplaceStmt = saveDisableReplaceStmt;
5698 CurrentBody = SaveCurrentBody;
5699 PropParentMap = 0;
5700 ImportedLocalExternalDecls.clear();
5701 // Now we snarf the rewritten text and stash it away for later use.
5702 std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
5703 RewrittenBlockExprs[BE] = Str;
5704
5705 Stmt *blockTranscribed = SynthBlockInitExpr(BE, InnerBlockDeclRefs);
5706
5707 //blockTranscribed->dump();
5708 ReplaceStmt(S, blockTranscribed);
5709 return blockTranscribed;
5710 }
5711 // Handle specific things.
5712 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
5713 return RewriteAtEncode(AtEncode);
5714
5715 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
5716 return RewriteAtSelector(AtSelector);
5717
5718 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
5719 return RewriteObjCStringLiteral(AtString);
Fariborz Jahanian55947042012-03-27 20:17:30 +00005720
5721 if (ObjCBoolLiteralExpr *BoolLitExpr = dyn_cast<ObjCBoolLiteralExpr>(S))
5722 return RewriteObjCBoolLiteralExpr(BoolLitExpr);
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00005723
Patrick Beardeb382ec2012-04-19 00:25:12 +00005724 if (ObjCBoxedExpr *BoxedExpr = dyn_cast<ObjCBoxedExpr>(S))
5725 return RewriteObjCBoxedExpr(BoxedExpr);
Fariborz Jahanian86cff602012-03-30 23:35:47 +00005726
5727 if (ObjCArrayLiteral *ArrayLitExpr = dyn_cast<ObjCArrayLiteral>(S))
5728 return RewriteObjCArrayLiteralExpr(ArrayLitExpr);
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00005729
5730 if (ObjCDictionaryLiteral *DictionaryLitExpr =
5731 dyn_cast<ObjCDictionaryLiteral>(S))
5732 return RewriteObjCDictionaryLiteralExpr(DictionaryLitExpr);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005733
5734 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
5735#if 0
5736 // Before we rewrite it, put the original message expression in a comment.
5737 SourceLocation startLoc = MessExpr->getLocStart();
5738 SourceLocation endLoc = MessExpr->getLocEnd();
5739
5740 const char *startBuf = SM->getCharacterData(startLoc);
5741 const char *endBuf = SM->getCharacterData(endLoc);
5742
5743 std::string messString;
5744 messString += "// ";
5745 messString.append(startBuf, endBuf-startBuf+1);
5746 messString += "\n";
5747
5748 // FIXME: Missing definition of
5749 // InsertText(clang::SourceLocation, char const*, unsigned int).
5750 // InsertText(startLoc, messString.c_str(), messString.size());
5751 // Tried this, but it didn't work either...
5752 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
5753#endif
5754 return RewriteMessageExpr(MessExpr);
5755 }
5756
Fariborz Jahanian042b91d2012-05-23 23:47:20 +00005757 if (ObjCAutoreleasePoolStmt *StmtAutoRelease =
5758 dyn_cast<ObjCAutoreleasePoolStmt>(S)) {
5759 return RewriteObjCAutoreleasePoolStmt(StmtAutoRelease);
5760 }
5761
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005762 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
5763 return RewriteObjCTryStmt(StmtTry);
5764
5765 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
5766 return RewriteObjCSynchronizedStmt(StmtTry);
5767
5768 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
5769 return RewriteObjCThrowStmt(StmtThrow);
5770
5771 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
5772 return RewriteObjCProtocolExpr(ProtocolExp);
5773
5774 if (ObjCForCollectionStmt *StmtForCollection =
5775 dyn_cast<ObjCForCollectionStmt>(S))
5776 return RewriteObjCForCollectionStmt(StmtForCollection,
5777 OrigStmtRange.getEnd());
5778 if (BreakStmt *StmtBreakStmt =
5779 dyn_cast<BreakStmt>(S))
5780 return RewriteBreakStmt(StmtBreakStmt);
5781 if (ContinueStmt *StmtContinueStmt =
5782 dyn_cast<ContinueStmt>(S))
5783 return RewriteContinueStmt(StmtContinueStmt);
5784
5785 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
5786 // and cast exprs.
5787 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
5788 // FIXME: What we're doing here is modifying the type-specifier that
5789 // precedes the first Decl. In the future the DeclGroup should have
5790 // a separate type-specifier that we can rewrite.
5791 // NOTE: We need to avoid rewriting the DeclStmt if it is within
5792 // the context of an ObjCForCollectionStmt. For example:
5793 // NSArray *someArray;
5794 // for (id <FooProtocol> index in someArray) ;
5795 // This is because RewriteObjCForCollectionStmt() does textual rewriting
5796 // and it depends on the original text locations/positions.
5797 if (Stmts.empty() || !IsDeclStmtInForeachHeader(DS))
5798 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
5799
5800 // Blocks rewrite rules.
5801 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
5802 DI != DE; ++DI) {
5803 Decl *SD = *DI;
5804 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
5805 if (isTopLevelBlockPointerType(ND->getType()))
5806 RewriteBlockPointerDecl(ND);
5807 else if (ND->getType()->isFunctionPointerType())
5808 CheckFunctionPointerDecl(ND->getType(), ND);
5809 if (VarDecl *VD = dyn_cast<VarDecl>(SD)) {
5810 if (VD->hasAttr<BlocksAttr>()) {
5811 static unsigned uniqueByrefDeclCount = 0;
5812 assert(!BlockByRefDeclNo.count(ND) &&
5813 "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
5814 BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
Fariborz Jahanian4fe261c2012-04-24 19:38:45 +00005815 RewriteByRefVar(VD, (DI == DS->decl_begin()), ((DI+1) == DE));
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005816 }
5817 else
5818 RewriteTypeOfDecl(VD);
5819 }
5820 }
5821 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(SD)) {
5822 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
5823 RewriteBlockPointerDecl(TD);
5824 else if (TD->getUnderlyingType()->isFunctionPointerType())
5825 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5826 }
5827 }
5828 }
5829
5830 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
5831 RewriteObjCQualifiedInterfaceTypes(CE);
5832
5833 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
5834 isa<DoStmt>(S) || isa<ForStmt>(S)) {
5835 assert(!Stmts.empty() && "Statement stack is empty");
5836 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
5837 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
5838 && "Statement stack mismatch");
5839 Stmts.pop_back();
5840 }
5841 // Handle blocks rewriting.
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005842 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
5843 ValueDecl *VD = DRE->getDecl();
5844 if (VD->hasAttr<BlocksAttr>())
5845 return RewriteBlockDeclRefExpr(DRE);
5846 if (HasLocalVariableExternalStorage(VD))
5847 return RewriteLocalVariableExternalStorage(DRE);
5848 }
5849
5850 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
5851 if (CE->getCallee()->getType()->isBlockPointerType()) {
5852 Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
5853 ReplaceStmt(S, BlockCall);
5854 return BlockCall;
5855 }
5856 }
5857 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
5858 RewriteCastExpr(CE);
5859 }
Fariborz Jahanianf1ee6872012-04-10 00:08:18 +00005860 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
5861 RewriteImplicitCastObjCExpr(ICE);
5862 }
Fariborz Jahanian43aa1c32012-04-16 22:14:01 +00005863#if 0
Fariborz Jahanian653b7cf2012-04-13 18:00:54 +00005864
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005865 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
5866 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(),
5867 ICE->getSubExpr(),
5868 SourceLocation());
5869 // Get the new text.
5870 std::string SStr;
5871 llvm::raw_string_ostream Buf(SStr);
Richard Smithd1420c62012-08-16 03:56:14 +00005872 Replacement->printPretty(Buf);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005873 const std::string &Str = Buf.str();
5874
5875 printf("CAST = %s\n", &Str[0]);
5876 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
5877 delete S;
5878 return Replacement;
5879 }
5880#endif
5881 // Return this stmt unmodified.
5882 return S;
5883}
5884
5885void RewriteModernObjC::RewriteRecordBody(RecordDecl *RD) {
5886 for (RecordDecl::field_iterator i = RD->field_begin(),
5887 e = RD->field_end(); i != e; ++i) {
David Blaikie581deb32012-06-06 20:45:41 +00005888 FieldDecl *FD = *i;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005889 if (isTopLevelBlockPointerType(FD->getType()))
5890 RewriteBlockPointerDecl(FD);
5891 if (FD->getType()->isObjCQualifiedIdType() ||
5892 FD->getType()->isObjCQualifiedInterfaceType())
5893 RewriteObjCQualifiedInterfaceTypes(FD);
5894 }
5895}
5896
5897/// HandleDeclInMainFile - This is called for each top-level decl defined in the
5898/// main file of the input.
5899void RewriteModernObjC::HandleDeclInMainFile(Decl *D) {
5900 switch (D->getKind()) {
5901 case Decl::Function: {
5902 FunctionDecl *FD = cast<FunctionDecl>(D);
5903 if (FD->isOverloadedOperator())
5904 return;
5905
5906 // Since function prototypes don't have ParmDecl's, we check the function
5907 // prototype. This enables us to rewrite function declarations and
5908 // definitions using the same code.
5909 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
5910
Argyrios Kyrtzidis9335df32012-02-12 04:48:45 +00005911 if (!FD->isThisDeclarationADefinition())
5912 break;
5913
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005914 // FIXME: If this should support Obj-C++, support CXXTryStmt
5915 if (CompoundStmt *Body = dyn_cast_or_null<CompoundStmt>(FD->getBody())) {
5916 CurFunctionDef = FD;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005917 CurrentBody = Body;
5918 Body =
5919 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5920 FD->setBody(Body);
5921 CurrentBody = 0;
5922 if (PropParentMap) {
5923 delete PropParentMap;
5924 PropParentMap = 0;
5925 }
5926 // This synthesizes and inserts the block "impl" struct, invoke function,
5927 // and any copy/dispose helper functions.
5928 InsertBlockLiteralsWithinFunction(FD);
Fariborz Jahanian96205962012-11-06 17:30:23 +00005929 RewriteLineDirective(D);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005930 CurFunctionDef = 0;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005931 }
5932 break;
5933 }
5934 case Decl::ObjCMethod: {
5935 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(D);
5936 if (CompoundStmt *Body = MD->getCompoundBody()) {
5937 CurMethodDef = MD;
5938 CurrentBody = Body;
5939 Body =
5940 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5941 MD->setBody(Body);
5942 CurrentBody = 0;
5943 if (PropParentMap) {
5944 delete PropParentMap;
5945 PropParentMap = 0;
5946 }
5947 InsertBlockLiteralsWithinMethod(MD);
Fariborz Jahanian96205962012-11-06 17:30:23 +00005948 RewriteLineDirective(D);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005949 CurMethodDef = 0;
5950 }
5951 break;
5952 }
5953 case Decl::ObjCImplementation: {
5954 ObjCImplementationDecl *CI = cast<ObjCImplementationDecl>(D);
5955 ClassImplementation.push_back(CI);
5956 break;
5957 }
5958 case Decl::ObjCCategoryImpl: {
5959 ObjCCategoryImplDecl *CI = cast<ObjCCategoryImplDecl>(D);
5960 CategoryImplementation.push_back(CI);
5961 break;
5962 }
5963 case Decl::Var: {
5964 VarDecl *VD = cast<VarDecl>(D);
5965 RewriteObjCQualifiedInterfaceTypes(VD);
5966 if (isTopLevelBlockPointerType(VD->getType()))
5967 RewriteBlockPointerDecl(VD);
5968 else if (VD->getType()->isFunctionPointerType()) {
5969 CheckFunctionPointerDecl(VD->getType(), VD);
5970 if (VD->getInit()) {
5971 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
5972 RewriteCastExpr(CE);
5973 }
5974 }
5975 } else if (VD->getType()->isRecordType()) {
5976 RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
5977 if (RD->isCompleteDefinition())
5978 RewriteRecordBody(RD);
5979 }
5980 if (VD->getInit()) {
5981 GlobalVarDecl = VD;
5982 CurrentBody = VD->getInit();
5983 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
5984 CurrentBody = 0;
5985 if (PropParentMap) {
5986 delete PropParentMap;
5987 PropParentMap = 0;
5988 }
5989 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(), VD->getName());
5990 GlobalVarDecl = 0;
5991
5992 // This is needed for blocks.
5993 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
5994 RewriteCastExpr(CE);
5995 }
5996 }
5997 break;
5998 }
5999 case Decl::TypeAlias:
6000 case Decl::Typedef: {
6001 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
6002 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
6003 RewriteBlockPointerDecl(TD);
6004 else if (TD->getUnderlyingType()->isFunctionPointerType())
6005 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
6006 }
6007 break;
6008 }
6009 case Decl::CXXRecord:
6010 case Decl::Record: {
6011 RecordDecl *RD = cast<RecordDecl>(D);
6012 if (RD->isCompleteDefinition())
6013 RewriteRecordBody(RD);
6014 break;
6015 }
6016 default:
6017 break;
6018 }
6019 // Nothing yet.
6020}
6021
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00006022/// Write_ProtocolExprReferencedMetadata - This routine writer out the
6023/// protocol reference symbols in the for of:
6024/// struct _protocol_t *PROTOCOL_REF = &PROTOCOL_METADATA.
6025static void Write_ProtocolExprReferencedMetadata(ASTContext *Context,
6026 ObjCProtocolDecl *PDecl,
6027 std::string &Result) {
6028 // Also output .objc_protorefs$B section and its meta-data.
6029 if (Context->getLangOpts().MicrosoftExt)
Fariborz Jahanianbd78cfa2012-04-27 21:39:49 +00006030 Result += "static ";
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00006031 Result += "struct _protocol_t *";
6032 Result += "_OBJC_PROTOCOL_REFERENCE_$_";
6033 Result += PDecl->getNameAsString();
6034 Result += " = &";
6035 Result += "_OBJC_PROTOCOL_"; Result += PDecl->getNameAsString();
6036 Result += ";\n";
6037}
6038
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006039void RewriteModernObjC::HandleTranslationUnit(ASTContext &C) {
6040 if (Diags.hasErrorOccurred())
6041 return;
6042
6043 RewriteInclude();
6044
Fariborz Jahanian31c4a4b2013-02-07 22:50:40 +00006045 for (unsigned i = 0, e = FunctionDefinitionsSeen.size(); i < e; i++) {
6046 // translation of function bodies were postponed untill all class and
6047 // their extensions and implementations are seen. This is because, we
6048 // cannot build grouping structs for bitfields untill they are all seen.
6049 FunctionDecl *FDecl = FunctionDefinitionsSeen[i];
6050 HandleTopLevelSingleDecl(FDecl);
6051 }
6052
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006053 // Here's a great place to add any extra declarations that may be needed.
6054 // Write out meta data for each @protocol(<expr>).
6055 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00006056 E = ProtocolExprDecls.end(); I != E; ++I) {
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006057 RewriteObjCProtocolMetaData(*I, Preamble);
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00006058 Write_ProtocolExprReferencedMetadata(Context, (*I), Preamble);
6059 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006060
6061 InsertText(SM->getLocForStartOfFile(MainFileID), Preamble, false);
Fariborz Jahanian163d3ce2012-05-08 23:54:35 +00006062
6063 if (ClassImplementation.size() || CategoryImplementation.size())
6064 RewriteImplementations();
6065
Fariborz Jahanian57317782012-02-21 23:58:41 +00006066 for (unsigned i = 0, e = ObjCInterfacesSeen.size(); i < e; i++) {
6067 ObjCInterfaceDecl *CDecl = ObjCInterfacesSeen[i];
6068 // Write struct declaration for the class matching its ivar declarations.
6069 // Note that for modern abi, this is postponed until the end of TU
6070 // because class extensions and the implementation might declare their own
6071 // private ivars.
6072 RewriteInterfaceDecl(CDecl);
6073 }
Fariborz Jahanian31c4a4b2013-02-07 22:50:40 +00006074
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006075 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
6076 // we are done.
6077 if (const RewriteBuffer *RewriteBuf =
6078 Rewrite.getRewriteBufferFor(MainFileID)) {
6079 //printf("Changed:\n");
6080 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
6081 } else {
6082 llvm::errs() << "No changes\n";
6083 }
6084
6085 if (ClassImplementation.size() || CategoryImplementation.size() ||
6086 ProtocolExprDecls.size()) {
6087 // Rewrite Objective-c meta data*
6088 std::string ResultStr;
6089 RewriteMetaDataIntoBuffer(ResultStr);
6090 // Emit metadata.
6091 *OutFile << ResultStr;
6092 }
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00006093 // Emit ImageInfo;
6094 {
6095 std::string ResultStr;
6096 WriteImageInfo(ResultStr);
6097 *OutFile << ResultStr;
6098 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006099 OutFile->flush();
6100}
6101
6102void RewriteModernObjC::Initialize(ASTContext &context) {
6103 InitializeCommon(context);
6104
Fariborz Jahanian6991bc52012-03-10 17:45:38 +00006105 Preamble += "#ifndef __OBJC2__\n";
6106 Preamble += "#define __OBJC2__\n";
6107 Preamble += "#endif\n";
6108
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006109 // declaring objc_selector outside the parameter list removes a silly
6110 // scope related warning...
6111 if (IsHeader)
6112 Preamble = "#pragma once\n";
6113 Preamble += "struct objc_selector; struct objc_class;\n";
Fariborz Jahaniane2d87bc2012-04-12 23:52:52 +00006114 Preamble += "struct __rw_objc_super { \n\tstruct objc_object *object; ";
6115 Preamble += "\n\tstruct objc_object *superClass; ";
6116 // Add a constructor for creating temporary objects.
6117 Preamble += "\n\t__rw_objc_super(struct objc_object *o, struct objc_object *s) ";
6118 Preamble += ": object(o), superClass(s) {} ";
6119 Preamble += "\n};\n";
6120
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006121 if (LangOpts.MicrosoftExt) {
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00006122 // Define all sections using syntax that makes sense.
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00006123 // These are currently generated.
6124 Preamble += "\n#pragma section(\".objc_classlist$B\", long, read, write)\n";
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00006125 Preamble += "#pragma section(\".objc_catlist$B\", long, read, write)\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00006126 Preamble += "#pragma section(\".objc_imageinfo$B\", long, read, write)\n";
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006127 Preamble += "#pragma section(\".objc_nlclslist$B\", long, read, write)\n";
6128 Preamble += "#pragma section(\".objc_nlcatlist$B\", long, read, write)\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00006129 // These are generated but not necessary for functionality.
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00006130 Preamble += "#pragma section(\".cat_cls_meth$B\", long, read, write)\n";
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00006131 Preamble += "#pragma section(\".inst_meth$B\", long, read, write)\n";
6132 Preamble += "#pragma section(\".cls_meth$B\", long, read, write)\n";
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00006133 Preamble += "#pragma section(\".objc_ivar$B\", long, read, write)\n";
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00006134
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00006135 // These need be generated for performance. Currently they are not,
6136 // using API calls instead.
6137 Preamble += "#pragma section(\".objc_selrefs$B\", long, read, write)\n";
6138 Preamble += "#pragma section(\".objc_classrefs$B\", long, read, write)\n";
6139 Preamble += "#pragma section(\".objc_superrefs$B\", long, read, write)\n";
6140
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006141 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006142 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
6143 Preamble += "typedef struct objc_object Protocol;\n";
6144 Preamble += "#define _REWRITER_typedef_Protocol\n";
6145 Preamble += "#endif\n";
6146 if (LangOpts.MicrosoftExt) {
6147 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
6148 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
Fariborz Jahanian5cf6b6c2012-03-21 23:41:04 +00006149 }
6150 else
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006151 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
Fariborz Jahanian5cf6b6c2012-03-21 23:41:04 +00006152
6153 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend(void);\n";
6154 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSendSuper(void);\n";
6155 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend_stret(void);\n";
6156 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSendSuper_stret(void);\n";
6157 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend_fpret(void);\n";
6158
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00006159 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *objc_getClass";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006160 Preamble += "(const char *);\n";
6161 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *class_getSuperclass";
6162 Preamble += "(struct objc_class *);\n";
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00006163 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *objc_getMetaClass";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006164 Preamble += "(const char *);\n";
Fariborz Jahanian55261af2012-03-19 18:11:32 +00006165 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw( struct objc_object *);\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006166 // @synchronized hooks.
Aaron Ballman2d234d732012-09-06 16:44:16 +00006167 Preamble += "__OBJC_RW_DLLIMPORT int objc_sync_enter( struct objc_object *);\n";
6168 Preamble += "__OBJC_RW_DLLIMPORT int objc_sync_exit( struct objc_object *);\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006169 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
6170 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
6171 Preamble += "struct __objcFastEnumerationState {\n\t";
6172 Preamble += "unsigned long state;\n\t";
6173 Preamble += "void **itemsPtr;\n\t";
6174 Preamble += "unsigned long *mutationsPtr;\n\t";
6175 Preamble += "unsigned long extra[5];\n};\n";
6176 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
6177 Preamble += "#define __FASTENUMERATIONSTATE\n";
6178 Preamble += "#endif\n";
6179 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
6180 Preamble += "struct __NSConstantStringImpl {\n";
6181 Preamble += " int *isa;\n";
6182 Preamble += " int flags;\n";
6183 Preamble += " char *str;\n";
6184 Preamble += " long length;\n";
6185 Preamble += "};\n";
6186 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
6187 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
6188 Preamble += "#else\n";
6189 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
6190 Preamble += "#endif\n";
6191 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
6192 Preamble += "#endif\n";
6193 // Blocks preamble.
6194 Preamble += "#ifndef BLOCK_IMPL\n";
6195 Preamble += "#define BLOCK_IMPL\n";
6196 Preamble += "struct __block_impl {\n";
6197 Preamble += " void *isa;\n";
6198 Preamble += " int Flags;\n";
6199 Preamble += " int Reserved;\n";
6200 Preamble += " void *FuncPtr;\n";
6201 Preamble += "};\n";
6202 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
6203 Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
6204 Preamble += "extern \"C\" __declspec(dllexport) "
6205 "void _Block_object_assign(void *, const void *, const int);\n";
6206 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
6207 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
6208 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
6209 Preamble += "#else\n";
6210 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
6211 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
6212 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
6213 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
6214 Preamble += "#endif\n";
6215 Preamble += "#endif\n";
6216 if (LangOpts.MicrosoftExt) {
6217 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
6218 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
6219 Preamble += "#ifndef KEEP_ATTRIBUTES\n"; // We use this for clang tests.
6220 Preamble += "#define __attribute__(X)\n";
6221 Preamble += "#endif\n";
Fariborz Jahanian5ce28272012-04-12 16:33:31 +00006222 Preamble += "#ifndef __weak\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006223 Preamble += "#define __weak\n";
Fariborz Jahanian5ce28272012-04-12 16:33:31 +00006224 Preamble += "#endif\n";
6225 Preamble += "#ifndef __block\n";
6226 Preamble += "#define __block\n";
6227 Preamble += "#endif\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006228 }
6229 else {
6230 Preamble += "#define __block\n";
6231 Preamble += "#define __weak\n";
6232 }
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +00006233
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00006234 // Declarations required for modern objective-c array and dictionary literals.
6235 Preamble += "\n#include <stdarg.h>\n";
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00006236 Preamble += "struct __NSContainer_literal {\n";
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00006237 Preamble += " void * *arr;\n";
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00006238 Preamble += " __NSContainer_literal (unsigned int count, ...) {\n";
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00006239 Preamble += "\tva_list marker;\n";
6240 Preamble += "\tva_start(marker, count);\n";
6241 Preamble += "\tarr = new void *[count];\n";
6242 Preamble += "\tfor (unsigned i = 0; i < count; i++)\n";
6243 Preamble += "\t arr[i] = va_arg(marker, void *);\n";
6244 Preamble += "\tva_end( marker );\n";
6245 Preamble += " };\n";
Fariborz Jahanian13a9c022012-05-02 23:53:46 +00006246 Preamble += " ~__NSContainer_literal() {\n";
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00006247 Preamble += "\tdelete[] arr;\n";
6248 Preamble += " }\n";
6249 Preamble += "};\n";
6250
Fariborz Jahanian042b91d2012-05-23 23:47:20 +00006251 // Declaration required for implementation of @autoreleasepool statement.
6252 Preamble += "extern \"C\" __declspec(dllimport) void * objc_autoreleasePoolPush(void);\n";
6253 Preamble += "extern \"C\" __declspec(dllimport) void objc_autoreleasePoolPop(void *);\n\n";
6254 Preamble += "struct __AtAutoreleasePool {\n";
6255 Preamble += " __AtAutoreleasePool() {atautoreleasepoolobj = objc_autoreleasePoolPush();}\n";
6256 Preamble += " ~__AtAutoreleasePool() {objc_autoreleasePoolPop(atautoreleasepoolobj);}\n";
6257 Preamble += " void * atautoreleasepoolobj;\n";
6258 Preamble += "};\n";
6259
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006260 // NOTE! Windows uses LLP64 for 64bit mode. So, cast pointer to long long
6261 // as this avoids warning in any 64bit/32bit compilation model.
6262 Preamble += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long long) &((TYPE *)0)->MEMBER)\n";
6263}
6264
6265/// RewriteIvarOffsetComputation - This rutine synthesizes computation of
6266/// ivar offset.
6267void RewriteModernObjC::RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
6268 std::string &Result) {
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00006269 Result += "__OFFSETOFIVAR__(struct ";
6270 Result += ivar->getContainingInterface()->getNameAsString();
6271 if (LangOpts.MicrosoftExt)
6272 Result += "_IMPL";
6273 Result += ", ";
6274 if (ivar->isBitField())
6275 ObjCIvarBitfieldGroupDecl(ivar, Result);
6276 else
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006277 Result += ivar->getNameAsString();
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00006278 Result += ")";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006279}
6280
6281/// WriteModernMetadataDeclarations - Writes out metadata declarations for modern ABI.
6282/// struct _prop_t {
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006283/// const char *name;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006284/// char *attributes;
6285/// }
6286
6287/// struct _prop_list_t {
6288/// uint32_t entsize; // sizeof(struct _prop_t)
6289/// uint32_t count_of_properties;
6290/// struct _prop_t prop_list[count_of_properties];
6291/// }
6292
6293/// struct _protocol_t;
6294
6295/// struct _protocol_list_t {
6296/// long protocol_count; // Note, this is 32/64 bit
6297/// struct _protocol_t * protocol_list[protocol_count];
6298/// }
6299
6300/// struct _objc_method {
6301/// SEL _cmd;
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006302/// const char *method_type;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006303/// char *_imp;
6304/// }
6305
6306/// struct _method_list_t {
6307/// uint32_t entsize; // sizeof(struct _objc_method)
6308/// uint32_t method_count;
6309/// struct _objc_method method_list[method_count];
6310/// }
6311
6312/// struct _protocol_t {
6313/// id isa; // NULL
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006314/// const char *protocol_name;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006315/// const struct _protocol_list_t * protocol_list; // super protocols
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006316/// const struct method_list_t *instance_methods;
6317/// const struct method_list_t *class_methods;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006318/// const struct method_list_t *optionalInstanceMethods;
6319/// const struct method_list_t *optionalClassMethods;
6320/// const struct _prop_list_t * properties;
6321/// const uint32_t size; // sizeof(struct _protocol_t)
6322/// const uint32_t flags; // = 0
6323/// const char ** extendedMethodTypes;
6324/// }
6325
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006326/// struct _ivar_t {
6327/// unsigned long int *offset; // pointer to ivar offset location
Fariborz Jahanianae932952012-02-10 20:47:10 +00006328/// const char *name;
6329/// const char *type;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006330/// uint32_t alignment;
6331/// uint32_t size;
6332/// }
6333
6334/// struct _ivar_list_t {
6335/// uint32 entsize; // sizeof(struct _ivar_t)
6336/// uint32 count;
Fariborz Jahanianae932952012-02-10 20:47:10 +00006337/// struct _ivar_t list[count];
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006338/// }
6339
6340/// struct _class_ro_t {
Fariborz Jahanian249cd102012-03-24 16:53:16 +00006341/// uint32_t flags;
6342/// uint32_t instanceStart;
6343/// uint32_t instanceSize;
6344/// uint32_t reserved; // only when building for 64bit targets
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006345/// const uint8_t *ivarLayout;
6346/// const char *name;
6347/// const struct _method_list_t *baseMethods;
6348/// const struct _protocol_list_t *baseProtocols;
6349/// const struct _ivar_list_t *ivars;
6350/// const uint8_t *weakIvarLayout;
6351/// const struct _prop_list_t *properties;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006352/// }
6353
6354/// struct _class_t {
6355/// struct _class_t *isa;
Fariborz Jahanianfd4ce2c2012-03-20 17:34:50 +00006356/// struct _class_t *superclass;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006357/// void *cache;
6358/// IMP *vtable;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006359/// struct _class_ro_t *ro;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006360/// }
6361
6362/// struct _category_t {
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006363/// const char *name;
Fariborz Jahanian4b2fe6e2012-03-20 21:41:28 +00006364/// struct _class_t *cls;
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006365/// const struct _method_list_t *instance_methods;
6366/// const struct _method_list_t *class_methods;
6367/// const struct _protocol_list_t *protocols;
6368/// const struct _prop_list_t *properties;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006369/// }
6370
6371/// MessageRefTy - LLVM for:
6372/// struct _message_ref_t {
6373/// IMP messenger;
6374/// SEL name;
6375/// };
6376
6377/// SuperMessageRefTy - LLVM for:
6378/// struct _super_message_ref_t {
6379/// SUPER_IMP messenger;
6380/// SEL name;
6381/// };
6382
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00006383static void WriteModernMetadataDeclarations(ASTContext *Context, std::string &Result) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006384 static bool meta_data_declared = false;
6385 if (meta_data_declared)
6386 return;
6387
6388 Result += "\nstruct _prop_t {\n";
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006389 Result += "\tconst char *name;\n";
6390 Result += "\tconst char *attributes;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006391 Result += "};\n";
6392
6393 Result += "\nstruct _protocol_t;\n";
6394
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006395 Result += "\nstruct _objc_method {\n";
6396 Result += "\tstruct objc_selector * _cmd;\n";
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006397 Result += "\tconst char *method_type;\n";
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006398 Result += "\tvoid *_imp;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006399 Result += "};\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006400
6401 Result += "\nstruct _protocol_t {\n";
6402 Result += "\tvoid * isa; // NULL\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006403 Result += "\tconst char *protocol_name;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006404 Result += "\tconst struct _protocol_list_t * protocol_list; // super protocols\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006405 Result += "\tconst struct method_list_t *instance_methods;\n";
6406 Result += "\tconst struct method_list_t *class_methods;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006407 Result += "\tconst struct method_list_t *optionalInstanceMethods;\n";
6408 Result += "\tconst struct method_list_t *optionalClassMethods;\n";
6409 Result += "\tconst struct _prop_list_t * properties;\n";
6410 Result += "\tconst unsigned int size; // sizeof(struct _protocol_t)\n";
6411 Result += "\tconst unsigned int flags; // = 0\n";
6412 Result += "\tconst char ** extendedMethodTypes;\n";
6413 Result += "};\n";
6414
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006415 Result += "\nstruct _ivar_t {\n";
6416 Result += "\tunsigned long int *offset; // pointer to ivar offset location\n";
Fariborz Jahanianae932952012-02-10 20:47:10 +00006417 Result += "\tconst char *name;\n";
6418 Result += "\tconst char *type;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006419 Result += "\tunsigned int alignment;\n";
6420 Result += "\tunsigned int size;\n";
6421 Result += "};\n";
6422
6423 Result += "\nstruct _class_ro_t {\n";
Fariborz Jahanian249cd102012-03-24 16:53:16 +00006424 Result += "\tunsigned int flags;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006425 Result += "\tunsigned int instanceStart;\n";
Fariborz Jahanian249cd102012-03-24 16:53:16 +00006426 Result += "\tunsigned int instanceSize;\n";
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00006427 const llvm::Triple &Triple(Context->getTargetInfo().getTriple());
6428 if (Triple.getArch() == llvm::Triple::x86_64)
Fariborz Jahanian249cd102012-03-24 16:53:16 +00006429 Result += "\tunsigned int reserved;\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006430 Result += "\tconst unsigned char *ivarLayout;\n";
6431 Result += "\tconst char *name;\n";
6432 Result += "\tconst struct _method_list_t *baseMethods;\n";
6433 Result += "\tconst struct _objc_protocol_list *baseProtocols;\n";
6434 Result += "\tconst struct _ivar_list_t *ivars;\n";
6435 Result += "\tconst unsigned char *weakIvarLayout;\n";
6436 Result += "\tconst struct _prop_list_t *properties;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006437 Result += "};\n";
6438
6439 Result += "\nstruct _class_t {\n";
6440 Result += "\tstruct _class_t *isa;\n";
Fariborz Jahanianfd4ce2c2012-03-20 17:34:50 +00006441 Result += "\tstruct _class_t *superclass;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006442 Result += "\tvoid *cache;\n";
6443 Result += "\tvoid *vtable;\n";
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006444 Result += "\tstruct _class_ro_t *ro;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006445 Result += "};\n";
6446
6447 Result += "\nstruct _category_t {\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006448 Result += "\tconst char *name;\n";
Fariborz Jahanian4b2fe6e2012-03-20 21:41:28 +00006449 Result += "\tstruct _class_t *cls;\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006450 Result += "\tconst struct _method_list_t *instance_methods;\n";
6451 Result += "\tconst struct _method_list_t *class_methods;\n";
6452 Result += "\tconst struct _protocol_list_t *protocols;\n";
6453 Result += "\tconst struct _prop_list_t *properties;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006454 Result += "};\n";
6455
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006456 Result += "extern \"C\" __declspec(dllimport) struct objc_cache _objc_empty_cache;\n";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006457 Result += "#pragma warning(disable:4273)\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006458 meta_data_declared = true;
6459}
6460
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006461static void Write_protocol_list_t_TypeDecl(std::string &Result,
6462 long super_protocol_count) {
6463 Result += "struct /*_protocol_list_t*/"; Result += " {\n";
6464 Result += "\tlong protocol_count; // Note, this is 32/64 bit\n";
6465 Result += "\tstruct _protocol_t *super_protocols[";
6466 Result += utostr(super_protocol_count); Result += "];\n";
6467 Result += "}";
6468}
6469
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006470static void Write_method_list_t_TypeDecl(std::string &Result,
6471 unsigned int method_count) {
6472 Result += "struct /*_method_list_t*/"; Result += " {\n";
6473 Result += "\tunsigned int entsize; // sizeof(struct _objc_method)\n";
6474 Result += "\tunsigned int method_count;\n";
6475 Result += "\tstruct _objc_method method_list[";
6476 Result += utostr(method_count); Result += "];\n";
6477 Result += "}";
6478}
6479
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006480static void Write__prop_list_t_TypeDecl(std::string &Result,
6481 unsigned int property_count) {
6482 Result += "struct /*_prop_list_t*/"; Result += " {\n";
6483 Result += "\tunsigned int entsize; // sizeof(struct _prop_t)\n";
6484 Result += "\tunsigned int count_of_properties;\n";
6485 Result += "\tstruct _prop_t prop_list[";
6486 Result += utostr(property_count); Result += "];\n";
6487 Result += "}";
6488}
6489
Fariborz Jahanianae932952012-02-10 20:47:10 +00006490static void Write__ivar_list_t_TypeDecl(std::string &Result,
6491 unsigned int ivar_count) {
6492 Result += "struct /*_ivar_list_t*/"; Result += " {\n";
6493 Result += "\tunsigned int entsize; // sizeof(struct _prop_t)\n";
6494 Result += "\tunsigned int count;\n";
6495 Result += "\tstruct _ivar_t ivar_list[";
6496 Result += utostr(ivar_count); Result += "];\n";
6497 Result += "}";
6498}
6499
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006500static void Write_protocol_list_initializer(ASTContext *Context, std::string &Result,
6501 ArrayRef<ObjCProtocolDecl *> SuperProtocols,
6502 StringRef VarName,
6503 StringRef ProtocolName) {
6504 if (SuperProtocols.size() > 0) {
6505 Result += "\nstatic ";
6506 Write_protocol_list_t_TypeDecl(Result, SuperProtocols.size());
6507 Result += " "; Result += VarName;
6508 Result += ProtocolName;
6509 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6510 Result += "\t"; Result += utostr(SuperProtocols.size()); Result += ",\n";
6511 for (unsigned i = 0, e = SuperProtocols.size(); i < e; i++) {
6512 ObjCProtocolDecl *SuperPD = SuperProtocols[i];
6513 Result += "\t&"; Result += "_OBJC_PROTOCOL_";
6514 Result += SuperPD->getNameAsString();
6515 if (i == e-1)
6516 Result += "\n};\n";
6517 else
6518 Result += ",\n";
6519 }
6520 }
6521}
6522
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006523static void Write_method_list_t_initializer(RewriteModernObjC &RewriteObj,
6524 ASTContext *Context, std::string &Result,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006525 ArrayRef<ObjCMethodDecl *> Methods,
6526 StringRef VarName,
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006527 StringRef TopLevelDeclName,
6528 bool MethodImpl) {
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006529 if (Methods.size() > 0) {
6530 Result += "\nstatic ";
6531 Write_method_list_t_TypeDecl(Result, Methods.size());
6532 Result += " "; Result += VarName;
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006533 Result += TopLevelDeclName;
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006534 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6535 Result += "\t"; Result += "sizeof(_objc_method)"; Result += ",\n";
6536 Result += "\t"; Result += utostr(Methods.size()); Result += ",\n";
6537 for (unsigned i = 0, e = Methods.size(); i < e; i++) {
6538 ObjCMethodDecl *MD = Methods[i];
6539 if (i == 0)
6540 Result += "\t{{(struct objc_selector *)\"";
6541 else
6542 Result += "\t{(struct objc_selector *)\"";
6543 Result += (MD)->getSelector().getAsString(); Result += "\"";
6544 Result += ", ";
6545 std::string MethodTypeString;
6546 Context->getObjCEncodingForMethodDecl(MD, MethodTypeString);
6547 Result += "\""; Result += MethodTypeString; Result += "\"";
6548 Result += ", ";
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006549 if (!MethodImpl)
6550 Result += "0";
6551 else {
6552 Result += "(void *)";
6553 Result += RewriteObj.MethodInternalNames[MD];
6554 }
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006555 if (i == e-1)
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006556 Result += "}}\n";
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006557 else
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006558 Result += "},\n";
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006559 }
6560 Result += "};\n";
6561 }
6562}
6563
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006564static void Write_prop_list_t_initializer(RewriteModernObjC &RewriteObj,
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006565 ASTContext *Context, std::string &Result,
6566 ArrayRef<ObjCPropertyDecl *> Properties,
6567 const Decl *Container,
6568 StringRef VarName,
6569 StringRef ProtocolName) {
6570 if (Properties.size() > 0) {
6571 Result += "\nstatic ";
6572 Write__prop_list_t_TypeDecl(Result, Properties.size());
6573 Result += " "; Result += VarName;
6574 Result += ProtocolName;
6575 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6576 Result += "\t"; Result += "sizeof(_prop_t)"; Result += ",\n";
6577 Result += "\t"; Result += utostr(Properties.size()); Result += ",\n";
6578 for (unsigned i = 0, e = Properties.size(); i < e; i++) {
6579 ObjCPropertyDecl *PropDecl = Properties[i];
6580 if (i == 0)
6581 Result += "\t{{\"";
6582 else
6583 Result += "\t{\"";
6584 Result += PropDecl->getName(); Result += "\",";
6585 std::string PropertyTypeString, QuotePropertyTypeString;
6586 Context->getObjCEncodingForPropertyDecl(PropDecl, Container, PropertyTypeString);
6587 RewriteObj.QuoteDoublequotes(PropertyTypeString, QuotePropertyTypeString);
6588 Result += "\""; Result += QuotePropertyTypeString; Result += "\"";
6589 if (i == e-1)
6590 Result += "}}\n";
6591 else
6592 Result += "},\n";
6593 }
6594 Result += "};\n";
6595 }
6596}
6597
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006598// Metadata flags
6599enum MetaDataDlags {
6600 CLS = 0x0,
6601 CLS_META = 0x1,
6602 CLS_ROOT = 0x2,
6603 OBJC2_CLS_HIDDEN = 0x10,
6604 CLS_EXCEPTION = 0x20,
6605
6606 /// (Obsolete) ARC-specific: this class has a .release_ivars method
6607 CLS_HAS_IVAR_RELEASER = 0x40,
6608 /// class was compiled with -fobjc-arr
6609 CLS_COMPILED_BY_ARC = 0x80 // (1<<7)
6610};
6611
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006612static void Write__class_ro_t_initializer(ASTContext *Context, std::string &Result,
6613 unsigned int flags,
6614 const std::string &InstanceStart,
6615 const std::string &InstanceSize,
6616 ArrayRef<ObjCMethodDecl *>baseMethods,
6617 ArrayRef<ObjCProtocolDecl *>baseProtocols,
6618 ArrayRef<ObjCIvarDecl *>ivars,
6619 ArrayRef<ObjCPropertyDecl *>Properties,
6620 StringRef VarName,
6621 StringRef ClassName) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006622 Result += "\nstatic struct _class_ro_t ";
6623 Result += VarName; Result += ClassName;
6624 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6625 Result += "\t";
6626 Result += llvm::utostr(flags); Result += ", ";
6627 Result += InstanceStart; Result += ", ";
6628 Result += InstanceSize; Result += ", \n";
6629 Result += "\t";
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00006630 const llvm::Triple &Triple(Context->getTargetInfo().getTriple());
6631 if (Triple.getArch() == llvm::Triple::x86_64)
6632 // uint32_t const reserved; // only when building for 64bit targets
6633 Result += "(unsigned int)0, \n\t";
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006634 // const uint8_t * const ivarLayout;
6635 Result += "0, \n\t";
6636 Result += "\""; Result += ClassName; Result += "\",\n\t";
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006637 bool metaclass = ((flags & CLS_META) != 0);
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006638 if (baseMethods.size() > 0) {
6639 Result += "(const struct _method_list_t *)&";
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006640 if (metaclass)
6641 Result += "_OBJC_$_CLASS_METHODS_";
6642 else
6643 Result += "_OBJC_$_INSTANCE_METHODS_";
6644 Result += ClassName;
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006645 Result += ",\n\t";
6646 }
6647 else
6648 Result += "0, \n\t";
6649
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006650 if (!metaclass && baseProtocols.size() > 0) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006651 Result += "(const struct _objc_protocol_list *)&";
6652 Result += "_OBJC_CLASS_PROTOCOLS_$_"; Result += ClassName;
6653 Result += ",\n\t";
6654 }
6655 else
6656 Result += "0, \n\t";
6657
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006658 if (!metaclass && ivars.size() > 0) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006659 Result += "(const struct _ivar_list_t *)&";
6660 Result += "_OBJC_$_INSTANCE_VARIABLES_"; Result += ClassName;
6661 Result += ",\n\t";
6662 }
6663 else
6664 Result += "0, \n\t";
6665
6666 // weakIvarLayout
6667 Result += "0, \n\t";
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006668 if (!metaclass && Properties.size() > 0) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006669 Result += "(const struct _prop_list_t *)&";
Fariborz Jahanianeeabf382012-02-16 21:57:59 +00006670 Result += "_OBJC_$_PROP_LIST_"; Result += ClassName;
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006671 Result += ",\n";
6672 }
6673 else
6674 Result += "0, \n";
6675
6676 Result += "};\n";
6677}
6678
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006679static void Write_class_t(ASTContext *Context, std::string &Result,
6680 StringRef VarName,
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006681 const ObjCInterfaceDecl *CDecl, bool metaclass) {
6682 bool rootClass = (!CDecl->getSuperClass());
6683 const ObjCInterfaceDecl *RootClass = CDecl;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006684
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006685 if (!rootClass) {
6686 // Find the Root class
6687 RootClass = CDecl->getSuperClass();
6688 while (RootClass->getSuperClass()) {
6689 RootClass = RootClass->getSuperClass();
6690 }
6691 }
6692
6693 if (metaclass && rootClass) {
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006694 // Need to handle a case of use of forward declaration.
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00006695 Result += "\n";
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006696 Result += "extern \"C\" ";
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00006697 if (CDecl->getImplementation())
6698 Result += "__declspec(dllexport) ";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006699 else
6700 Result += "__declspec(dllimport) ";
6701
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006702 Result += "struct _class_t OBJC_CLASS_$_";
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006703 Result += CDecl->getNameAsString();
6704 Result += ";\n";
6705 }
6706 // Also, for possibility of 'super' metadata class not having been defined yet.
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006707 if (!rootClass) {
Fariborz Jahanian868e9852012-03-29 19:04:10 +00006708 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00006709 Result += "\n";
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006710 Result += "extern \"C\" ";
Fariborz Jahanian868e9852012-03-29 19:04:10 +00006711 if (SuperClass->getImplementation())
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00006712 Result += "__declspec(dllexport) ";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006713 else
6714 Result += "__declspec(dllimport) ";
6715
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006716 Result += "struct _class_t ";
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00006717 Result += VarName;
Fariborz Jahanian868e9852012-03-29 19:04:10 +00006718 Result += SuperClass->getNameAsString();
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006719 Result += ";\n";
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006720
Fariborz Jahanian868e9852012-03-29 19:04:10 +00006721 if (metaclass && RootClass != SuperClass) {
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006722 Result += "extern \"C\" ";
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006723 if (RootClass->getImplementation())
6724 Result += "__declspec(dllexport) ";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006725 else
6726 Result += "__declspec(dllimport) ";
6727
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006728 Result += "struct _class_t ";
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006729 Result += VarName;
6730 Result += RootClass->getNameAsString();
6731 Result += ";\n";
6732 }
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006733 }
6734
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006735 Result += "\nextern \"C\" __declspec(dllexport) struct _class_t ";
6736 Result += VarName; Result += CDecl->getNameAsString();
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006737 Result += " __attribute__ ((used, section (\"__DATA,__objc_data\"))) = {\n";
6738 Result += "\t";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006739 if (metaclass) {
6740 if (!rootClass) {
6741 Result += "0, // &"; Result += VarName;
6742 Result += RootClass->getNameAsString();
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006743 Result += ",\n\t";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006744 Result += "0, // &"; Result += VarName;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006745 Result += CDecl->getSuperClass()->getNameAsString();
6746 Result += ",\n\t";
6747 }
6748 else {
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006749 Result += "0, // &"; Result += VarName;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006750 Result += CDecl->getNameAsString();
6751 Result += ",\n\t";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006752 Result += "0, // &OBJC_CLASS_$_"; Result += CDecl->getNameAsString();
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006753 Result += ",\n\t";
6754 }
6755 }
6756 else {
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006757 Result += "0, // &OBJC_METACLASS_$_";
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006758 Result += CDecl->getNameAsString();
6759 Result += ",\n\t";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006760 if (!rootClass) {
6761 Result += "0, // &"; Result += VarName;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006762 Result += CDecl->getSuperClass()->getNameAsString();
6763 Result += ",\n\t";
6764 }
6765 else
6766 Result += "0,\n\t";
6767 }
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006768 Result += "0, // (void *)&_objc_empty_cache,\n\t";
6769 Result += "0, // unused, was (void *)&_objc_empty_vtable,\n\t";
6770 if (metaclass)
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006771 Result += "&_OBJC_METACLASS_RO_$_";
6772 else
6773 Result += "&_OBJC_CLASS_RO_$_";
6774 Result += CDecl->getNameAsString();
6775 Result += ",\n};\n";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006776
6777 // Add static function to initialize some of the meta-data fields.
6778 // avoid doing it twice.
6779 if (metaclass)
6780 return;
6781
6782 const ObjCInterfaceDecl *SuperClass =
6783 rootClass ? CDecl : CDecl->getSuperClass();
6784
6785 Result += "static void OBJC_CLASS_SETUP_$_";
6786 Result += CDecl->getNameAsString();
6787 Result += "(void ) {\n";
6788 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
6789 Result += ".isa = "; Result += "&OBJC_METACLASS_$_";
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006790 Result += RootClass->getNameAsString(); Result += ";\n";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006791
6792 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006793 Result += ".superclass = ";
6794 if (rootClass)
6795 Result += "&OBJC_CLASS_$_";
6796 else
6797 Result += "&OBJC_METACLASS_$_";
6798
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006799 Result += SuperClass->getNameAsString(); Result += ";\n";
6800
6801 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
6802 Result += ".cache = "; Result += "&_objc_empty_cache"; Result += ";\n";
6803
6804 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6805 Result += ".isa = "; Result += "&OBJC_METACLASS_$_";
6806 Result += CDecl->getNameAsString(); Result += ";\n";
6807
6808 if (!rootClass) {
6809 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6810 Result += ".superclass = "; Result += "&OBJC_CLASS_$_";
6811 Result += SuperClass->getNameAsString(); Result += ";\n";
6812 }
6813
6814 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6815 Result += ".cache = "; Result += "&_objc_empty_cache"; Result += ";\n";
6816 Result += "}\n";
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006817}
6818
Fariborz Jahanian61186122012-02-17 18:40:41 +00006819static void Write_category_t(RewriteModernObjC &RewriteObj, ASTContext *Context,
6820 std::string &Result,
Fariborz Jahaniane0335782012-03-27 18:41:05 +00006821 ObjCCategoryDecl *CatDecl,
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006822 ObjCInterfaceDecl *ClassDecl,
Fariborz Jahanian61186122012-02-17 18:40:41 +00006823 ArrayRef<ObjCMethodDecl *> InstanceMethods,
6824 ArrayRef<ObjCMethodDecl *> ClassMethods,
6825 ArrayRef<ObjCProtocolDecl *> RefedProtocols,
6826 ArrayRef<ObjCPropertyDecl *> ClassProperties) {
Fariborz Jahaniane0335782012-03-27 18:41:05 +00006827 StringRef CatName = CatDecl->getName();
NAKAMURA Takumi20f89392012-03-21 03:21:46 +00006828 StringRef ClassName = ClassDecl->getName();
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00006829 // must declare an extern class object in case this class is not implemented
6830 // in this TU.
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006831 Result += "\n";
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006832 Result += "extern \"C\" ";
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006833 if (ClassDecl->getImplementation())
6834 Result += "__declspec(dllexport) ";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006835 else
6836 Result += "__declspec(dllimport) ";
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006837
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006838 Result += "struct _class_t ";
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00006839 Result += "OBJC_CLASS_$_"; Result += ClassName;
6840 Result += ";\n";
6841
Fariborz Jahanian61186122012-02-17 18:40:41 +00006842 Result += "\nstatic struct _category_t ";
6843 Result += "_OBJC_$_CATEGORY_";
6844 Result += ClassName; Result += "_$_"; Result += CatName;
6845 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = \n";
6846 Result += "{\n";
6847 Result += "\t\""; Result += ClassName; Result += "\",\n";
Fariborz Jahanian4b2fe6e2012-03-20 21:41:28 +00006848 Result += "\t0, // &"; Result += "OBJC_CLASS_$_"; Result += ClassName;
Fariborz Jahanian61186122012-02-17 18:40:41 +00006849 Result += ",\n";
6850 if (InstanceMethods.size() > 0) {
6851 Result += "\t(const struct _method_list_t *)&";
6852 Result += "_OBJC_$_CATEGORY_INSTANCE_METHODS_";
6853 Result += ClassName; Result += "_$_"; Result += CatName;
6854 Result += ",\n";
6855 }
6856 else
6857 Result += "\t0,\n";
6858
6859 if (ClassMethods.size() > 0) {
6860 Result += "\t(const struct _method_list_t *)&";
6861 Result += "_OBJC_$_CATEGORY_CLASS_METHODS_";
6862 Result += ClassName; Result += "_$_"; Result += CatName;
6863 Result += ",\n";
6864 }
6865 else
6866 Result += "\t0,\n";
6867
6868 if (RefedProtocols.size() > 0) {
6869 Result += "\t(const struct _protocol_list_t *)&";
6870 Result += "_OBJC_CATEGORY_PROTOCOLS_$_";
6871 Result += ClassName; Result += "_$_"; Result += CatName;
6872 Result += ",\n";
6873 }
6874 else
6875 Result += "\t0,\n";
6876
6877 if (ClassProperties.size() > 0) {
6878 Result += "\t(const struct _prop_list_t *)&"; Result += "_OBJC_$_PROP_LIST_";
6879 Result += ClassName; Result += "_$_"; Result += CatName;
6880 Result += ",\n";
6881 }
6882 else
6883 Result += "\t0,\n";
6884
6885 Result += "};\n";
Fariborz Jahanian4b2fe6e2012-03-20 21:41:28 +00006886
6887 // Add static function to initialize the class pointer in the category structure.
6888 Result += "static void OBJC_CATEGORY_SETUP_$_";
6889 Result += ClassDecl->getNameAsString();
6890 Result += "_$_";
6891 Result += CatName;
6892 Result += "(void ) {\n";
6893 Result += "\t_OBJC_$_CATEGORY_";
6894 Result += ClassDecl->getNameAsString();
6895 Result += "_$_";
6896 Result += CatName;
6897 Result += ".cls = "; Result += "&OBJC_CLASS_$_"; Result += ClassName;
6898 Result += ";\n}\n";
Fariborz Jahanian61186122012-02-17 18:40:41 +00006899}
6900
Fariborz Jahaniane0adbd82012-02-08 22:23:26 +00006901static void Write__extendedMethodTypes_initializer(RewriteModernObjC &RewriteObj,
6902 ASTContext *Context, std::string &Result,
6903 ArrayRef<ObjCMethodDecl *> Methods,
6904 StringRef VarName,
6905 StringRef ProtocolName) {
6906 if (Methods.size() == 0)
6907 return;
6908
6909 Result += "\nstatic const char *";
6910 Result += VarName; Result += ProtocolName;
6911 Result += " [] __attribute__ ((used, section (\"__DATA,__objc_const\"))) = \n";
6912 Result += "{\n";
6913 for (unsigned i = 0, e = Methods.size(); i < e; i++) {
6914 ObjCMethodDecl *MD = Methods[i];
6915 std::string MethodTypeString, QuoteMethodTypeString;
6916 Context->getObjCEncodingForMethodDecl(MD, MethodTypeString, true);
6917 RewriteObj.QuoteDoublequotes(MethodTypeString, QuoteMethodTypeString);
6918 Result += "\t\""; Result += QuoteMethodTypeString; Result += "\"";
6919 if (i == e-1)
6920 Result += "\n};\n";
6921 else {
6922 Result += ",\n";
6923 }
6924 }
6925}
6926
Fariborz Jahanianacee1c92012-04-11 21:12:36 +00006927static void Write_IvarOffsetVar(RewriteModernObjC &RewriteObj,
6928 ASTContext *Context,
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00006929 std::string &Result,
Fariborz Jahaniandb649232012-02-13 20:59:02 +00006930 ArrayRef<ObjCIvarDecl *> Ivars,
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006931 ObjCInterfaceDecl *CDecl) {
Fariborz Jahaniandb649232012-02-13 20:59:02 +00006932 // FIXME. visibilty of offset symbols may have to be set; for Darwin
6933 // this is what happens:
6934 /**
6935 if (Ivar->getAccessControl() == ObjCIvarDecl::Private ||
6936 Ivar->getAccessControl() == ObjCIvarDecl::Package ||
6937 Class->getVisibility() == HiddenVisibility)
6938 Visibility shoud be: HiddenVisibility;
6939 else
6940 Visibility shoud be: DefaultVisibility;
6941 */
6942
Fariborz Jahanian07e52882012-02-13 21:34:45 +00006943 Result += "\n";
6944 for (unsigned i =0, e = Ivars.size(); i < e; i++) {
6945 ObjCIvarDecl *IvarDecl = Ivars[i];
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00006946 if (Context->getLangOpts().MicrosoftExt)
6947 Result += "__declspec(allocate(\".objc_ivar$B\")) ";
6948
6949 if (!Context->getLangOpts().MicrosoftExt ||
6950 IvarDecl->getAccessControl() == ObjCIvarDecl::Private ||
Fariborz Jahanian117591f2012-03-10 01:34:42 +00006951 IvarDecl->getAccessControl() == ObjCIvarDecl::Package)
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006952 Result += "extern \"C\" unsigned long int ";
Fariborz Jahaniand1c84d32012-03-10 00:53:02 +00006953 else
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006954 Result += "extern \"C\" __declspec(dllexport) unsigned long int ";
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00006955 if (Ivars[i]->isBitField())
6956 RewriteObj.ObjCIvarBitfieldGroupOffset(IvarDecl, Result);
6957 else
6958 WriteInternalIvarName(CDecl, IvarDecl, Result);
Fariborz Jahanian07e52882012-02-13 21:34:45 +00006959 Result += " __attribute__ ((used, section (\"__DATA,__objc_ivar\")))";
6960 Result += " = ";
Fariborz Jahanianacee1c92012-04-11 21:12:36 +00006961 RewriteObj.RewriteIvarOffsetComputation(IvarDecl, Result);
6962 Result += ";\n";
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00006963 if (Ivars[i]->isBitField()) {
6964 // skip over rest of the ivar bitfields.
6965 SKIP_BITFIELDS(i , e, Ivars);
6966 }
Fariborz Jahaniandb649232012-02-13 20:59:02 +00006967 }
6968}
6969
Fariborz Jahanianae932952012-02-10 20:47:10 +00006970static void Write__ivar_list_t_initializer(RewriteModernObjC &RewriteObj,
6971 ASTContext *Context, std::string &Result,
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00006972 ArrayRef<ObjCIvarDecl *> OriginalIvars,
Fariborz Jahanianae932952012-02-10 20:47:10 +00006973 StringRef VarName,
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006974 ObjCInterfaceDecl *CDecl) {
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00006975 if (OriginalIvars.size() > 0) {
6976 Write_IvarOffsetVar(RewriteObj, Context, Result, OriginalIvars, CDecl);
6977 SmallVector<ObjCIvarDecl *, 8> Ivars;
6978 // strip off all but the first ivar bitfield from each group of ivars.
6979 // Such ivars in the ivar list table will be replaced by their grouping struct
6980 // 'ivar'.
6981 for (unsigned i = 0, e = OriginalIvars.size(); i < e; i++) {
6982 if (OriginalIvars[i]->isBitField()) {
6983 Ivars.push_back(OriginalIvars[i]);
6984 // skip over rest of the ivar bitfields.
6985 SKIP_BITFIELDS(i , e, OriginalIvars);
6986 }
6987 else
6988 Ivars.push_back(OriginalIvars[i]);
6989 }
Fariborz Jahanian07e52882012-02-13 21:34:45 +00006990
Fariborz Jahanianae932952012-02-10 20:47:10 +00006991 Result += "\nstatic ";
6992 Write__ivar_list_t_TypeDecl(Result, Ivars.size());
6993 Result += " "; Result += VarName;
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006994 Result += CDecl->getNameAsString();
Fariborz Jahanianae932952012-02-10 20:47:10 +00006995 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6996 Result += "\t"; Result += "sizeof(_ivar_t)"; Result += ",\n";
6997 Result += "\t"; Result += utostr(Ivars.size()); Result += ",\n";
6998 for (unsigned i =0, e = Ivars.size(); i < e; i++) {
6999 ObjCIvarDecl *IvarDecl = Ivars[i];
7000 if (i == 0)
7001 Result += "\t{{";
7002 else
7003 Result += "\t {";
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00007004 Result += "(unsigned long int *)&";
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00007005 if (Ivars[i]->isBitField())
7006 RewriteObj.ObjCIvarBitfieldGroupOffset(IvarDecl, Result);
7007 else
7008 WriteInternalIvarName(CDecl, IvarDecl, Result);
Fariborz Jahaniandb649232012-02-13 20:59:02 +00007009 Result += ", ";
Fariborz Jahanianae932952012-02-10 20:47:10 +00007010
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00007011 Result += "\"";
7012 if (Ivars[i]->isBitField())
7013 RewriteObj.ObjCIvarBitfieldGroupDecl(Ivars[i], Result);
7014 else
7015 Result += IvarDecl->getName();
7016 Result += "\", ";
7017
7018 QualType IVQT = IvarDecl->getType();
7019 if (IvarDecl->isBitField())
7020 IVQT = RewriteObj.GetGroupRecordTypeForObjCIvarBitfield(IvarDecl);
7021
Fariborz Jahanianae932952012-02-10 20:47:10 +00007022 std::string IvarTypeString, QuoteIvarTypeString;
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00007023 Context->getObjCEncodingForType(IVQT, IvarTypeString,
Fariborz Jahanianae932952012-02-10 20:47:10 +00007024 IvarDecl);
7025 RewriteObj.QuoteDoublequotes(IvarTypeString, QuoteIvarTypeString);
7026 Result += "\""; Result += QuoteIvarTypeString; Result += "\", ";
7027
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00007028 // FIXME. this alignment represents the host alignment and need be changed to
7029 // represent the target alignment.
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00007030 unsigned Align = Context->getTypeAlign(IVQT)/8;
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00007031 Align = llvm::Log2_32(Align);
Fariborz Jahanianae932952012-02-10 20:47:10 +00007032 Result += llvm::utostr(Align); Result += ", ";
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00007033 CharUnits Size = Context->getTypeSizeInChars(IVQT);
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00007034 Result += llvm::utostr(Size.getQuantity());
Fariborz Jahanianae932952012-02-10 20:47:10 +00007035 if (i == e-1)
7036 Result += "}}\n";
7037 else
7038 Result += "},\n";
7039 }
7040 Result += "};\n";
7041 }
7042}
7043
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007044/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00007045void RewriteModernObjC::RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl,
7046 std::string &Result) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007047
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007048 // Do not synthesize the protocol more than once.
7049 if (ObjCSynthesizedProtocols.count(PDecl->getCanonicalDecl()))
7050 return;
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00007051 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007052
7053 if (ObjCProtocolDecl *Def = PDecl->getDefinition())
7054 PDecl = Def;
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00007055 // Must write out all protocol definitions in current qualifier list,
7056 // and in their nested qualifiers before writing out current definition.
7057 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
7058 E = PDecl->protocol_end(); I != E; ++I)
7059 RewriteObjCProtocolMetaData(*I, Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007060
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00007061 // Construct method lists.
7062 std::vector<ObjCMethodDecl *> InstanceMethods, ClassMethods;
7063 std::vector<ObjCMethodDecl *> OptInstanceMethods, OptClassMethods;
7064 for (ObjCProtocolDecl::instmeth_iterator
7065 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
7066 I != E; ++I) {
7067 ObjCMethodDecl *MD = *I;
7068 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
7069 OptInstanceMethods.push_back(MD);
7070 } else {
7071 InstanceMethods.push_back(MD);
7072 }
7073 }
7074
7075 for (ObjCProtocolDecl::classmeth_iterator
7076 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
7077 I != E; ++I) {
7078 ObjCMethodDecl *MD = *I;
7079 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
7080 OptClassMethods.push_back(MD);
7081 } else {
7082 ClassMethods.push_back(MD);
7083 }
7084 }
Fariborz Jahaniane0adbd82012-02-08 22:23:26 +00007085 std::vector<ObjCMethodDecl *> AllMethods;
7086 for (unsigned i = 0, e = InstanceMethods.size(); i < e; i++)
7087 AllMethods.push_back(InstanceMethods[i]);
7088 for (unsigned i = 0, e = ClassMethods.size(); i < e; i++)
7089 AllMethods.push_back(ClassMethods[i]);
7090 for (unsigned i = 0, e = OptInstanceMethods.size(); i < e; i++)
7091 AllMethods.push_back(OptInstanceMethods[i]);
7092 for (unsigned i = 0, e = OptClassMethods.size(); i < e; i++)
7093 AllMethods.push_back(OptClassMethods[i]);
7094
7095 Write__extendedMethodTypes_initializer(*this, Context, Result,
7096 AllMethods,
7097 "_OBJC_PROTOCOL_METHOD_TYPES_",
7098 PDecl->getNameAsString());
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00007099 // Protocol's super protocol list
7100 std::vector<ObjCProtocolDecl *> SuperProtocols;
7101 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
7102 E = PDecl->protocol_end(); I != E; ++I)
7103 SuperProtocols.push_back(*I);
7104
7105 Write_protocol_list_initializer(Context, Result, SuperProtocols,
7106 "_OBJC_PROTOCOL_REFS_",
7107 PDecl->getNameAsString());
7108
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00007109 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00007110 "_OBJC_PROTOCOL_INSTANCE_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00007111 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00007112
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00007113 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00007114 "_OBJC_PROTOCOL_CLASS_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00007115 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00007116
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00007117 Write_method_list_t_initializer(*this, Context, Result, OptInstanceMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00007118 "_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00007119 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00007120
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00007121 Write_method_list_t_initializer(*this, Context, Result, OptClassMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00007122 "_OBJC_PROTOCOL_OPT_CLASS_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00007123 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00007124
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00007125 // Protocol's property metadata.
7126 std::vector<ObjCPropertyDecl *> ProtocolProperties;
7127 for (ObjCContainerDecl::prop_iterator I = PDecl->prop_begin(),
7128 E = PDecl->prop_end(); I != E; ++I)
David Blaikie581deb32012-06-06 20:45:41 +00007129 ProtocolProperties.push_back(*I);
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00007130
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00007131 Write_prop_list_t_initializer(*this, Context, Result, ProtocolProperties,
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00007132 /* Container */0,
7133 "_OBJC_PROTOCOL_PROPERTIES_",
7134 PDecl->getNameAsString());
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00007135
Fariborz Jahanian82848c22012-02-08 00:50:52 +00007136 // Writer out root metadata for current protocol: struct _protocol_t
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00007137 Result += "\n";
7138 if (LangOpts.MicrosoftExt)
Fariborz Jahanian8590d862012-04-14 17:13:08 +00007139 Result += "static ";
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00007140 Result += "struct _protocol_t _OBJC_PROTOCOL_";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007141 Result += PDecl->getNameAsString();
Fariborz Jahanian82848c22012-02-08 00:50:52 +00007142 Result += " __attribute__ ((used, section (\"__DATA,__datacoal_nt,coalesced\"))) = {\n";
7143 Result += "\t0,\n"; // id is; is null
7144 Result += "\t\""; Result += PDecl->getNameAsString(); Result += "\",\n";
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00007145 if (SuperProtocols.size() > 0) {
7146 Result += "\t(const struct _protocol_list_t *)&"; Result += "_OBJC_PROTOCOL_REFS_";
7147 Result += PDecl->getNameAsString(); Result += ",\n";
7148 }
7149 else
7150 Result += "\t0,\n";
Fariborz Jahanian82848c22012-02-08 00:50:52 +00007151 if (InstanceMethods.size() > 0) {
7152 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
7153 Result += PDecl->getNameAsString(); Result += ",\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007154 }
7155 else
Fariborz Jahanian82848c22012-02-08 00:50:52 +00007156 Result += "\t0,\n";
7157
7158 if (ClassMethods.size() > 0) {
7159 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_CLASS_METHODS_";
7160 Result += PDecl->getNameAsString(); Result += ",\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007161 }
7162 else
Fariborz Jahanian82848c22012-02-08 00:50:52 +00007163 Result += "\t0,\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007164
Fariborz Jahanian82848c22012-02-08 00:50:52 +00007165 if (OptInstanceMethods.size() > 0) {
7166 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_";
7167 Result += PDecl->getNameAsString(); Result += ",\n";
7168 }
7169 else
7170 Result += "\t0,\n";
7171
7172 if (OptClassMethods.size() > 0) {
7173 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_CLASS_METHODS_";
7174 Result += PDecl->getNameAsString(); Result += ",\n";
7175 }
7176 else
7177 Result += "\t0,\n";
7178
7179 if (ProtocolProperties.size() > 0) {
7180 Result += "\t(const struct _prop_list_t *)&_OBJC_PROTOCOL_PROPERTIES_";
7181 Result += PDecl->getNameAsString(); Result += ",\n";
7182 }
7183 else
7184 Result += "\t0,\n";
7185
7186 Result += "\t"; Result += "sizeof(_protocol_t)"; Result += ",\n";
7187 Result += "\t0,\n";
7188
Fariborz Jahaniane0adbd82012-02-08 22:23:26 +00007189 if (AllMethods.size() > 0) {
7190 Result += "\t(const char **)&"; Result += "_OBJC_PROTOCOL_METHOD_TYPES_";
7191 Result += PDecl->getNameAsString();
7192 Result += "\n};\n";
7193 }
7194 else
7195 Result += "\t0\n};\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00007196
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00007197 if (LangOpts.MicrosoftExt)
Fariborz Jahanian8590d862012-04-14 17:13:08 +00007198 Result += "static ";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00007199 Result += "struct _protocol_t *";
7200 Result += "_OBJC_LABEL_PROTOCOL_$_"; Result += PDecl->getNameAsString();
7201 Result += " = &_OBJC_PROTOCOL_"; Result += PDecl->getNameAsString();
7202 Result += ";\n";
Fariborz Jahanian82848c22012-02-08 00:50:52 +00007203
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007204 // Mark this protocol as having been generated.
7205 if (!ObjCSynthesizedProtocols.insert(PDecl->getCanonicalDecl()))
7206 llvm_unreachable("protocol already synthesized");
7207
7208}
7209
7210void RewriteModernObjC::RewriteObjCProtocolListMetaData(
7211 const ObjCList<ObjCProtocolDecl> &Protocols,
7212 StringRef prefix, StringRef ClassName,
7213 std::string &Result) {
7214 if (Protocols.empty()) return;
7215
7216 for (unsigned i = 0; i != Protocols.size(); i++)
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00007217 RewriteObjCProtocolMetaData(Protocols[i], Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007218
7219 // Output the top lovel protocol meta-data for the class.
7220 /* struct _objc_protocol_list {
7221 struct _objc_protocol_list *next;
7222 int protocol_count;
7223 struct _objc_protocol *class_protocols[];
7224 }
7225 */
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00007226 Result += "\n";
7227 if (LangOpts.MicrosoftExt)
7228 Result += "__declspec(allocate(\".cat_cls_meth$B\")) ";
7229 Result += "static struct {\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007230 Result += "\tstruct _objc_protocol_list *next;\n";
7231 Result += "\tint protocol_count;\n";
7232 Result += "\tstruct _objc_protocol *class_protocols[";
7233 Result += utostr(Protocols.size());
7234 Result += "];\n} _OBJC_";
7235 Result += prefix;
7236 Result += "_PROTOCOLS_";
7237 Result += ClassName;
7238 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
7239 "{\n\t0, ";
7240 Result += utostr(Protocols.size());
7241 Result += "\n";
7242
7243 Result += "\t,{&_OBJC_PROTOCOL_";
7244 Result += Protocols[0]->getNameAsString();
7245 Result += " \n";
7246
7247 for (unsigned i = 1; i != Protocols.size(); i++) {
7248 Result += "\t ,&_OBJC_PROTOCOL_";
7249 Result += Protocols[i]->getNameAsString();
7250 Result += "\n";
7251 }
7252 Result += "\t }\n};\n";
7253}
7254
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00007255/// hasObjCExceptionAttribute - Return true if this class or any super
7256/// class has the __objc_exception__ attribute.
7257/// FIXME. Move this to ASTContext.cpp as it is also used for IRGen.
7258static bool hasObjCExceptionAttribute(ASTContext &Context,
7259 const ObjCInterfaceDecl *OID) {
7260 if (OID->hasAttr<ObjCExceptionAttr>())
7261 return true;
7262 if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
7263 return hasObjCExceptionAttribute(Context, Super);
7264 return false;
7265}
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00007266
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007267void RewriteModernObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
7268 std::string &Result) {
7269 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
7270
7271 // Explicitly declared @interface's are already synthesized.
Fariborz Jahanianae932952012-02-10 20:47:10 +00007272 if (CDecl->isImplicitInterfaceDecl())
7273 assert(false &&
7274 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00007275
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00007276 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanianae932952012-02-10 20:47:10 +00007277 SmallVector<ObjCIvarDecl *, 8> IVars;
7278
7279 for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
7280 IVD; IVD = IVD->getNextIvar()) {
7281 // Ignore unnamed bit-fields.
7282 if (!IVD->getDeclName())
7283 continue;
7284 IVars.push_back(IVD);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007285 }
7286
Fariborz Jahanianae932952012-02-10 20:47:10 +00007287 Write__ivar_list_t_initializer(*this, Context, Result, IVars,
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00007288 "_OBJC_$_INSTANCE_VARIABLES_",
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00007289 CDecl);
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00007290
7291 // Build _objc_method_list for class's instance methods if needed
7292 SmallVector<ObjCMethodDecl *, 32>
7293 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
7294
7295 // If any of our property implementations have associated getters or
7296 // setters, produce metadata for them as well.
7297 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
7298 PropEnd = IDecl->propimpl_end();
7299 Prop != PropEnd; ++Prop) {
David Blaikie262bc182012-04-30 02:36:29 +00007300 if (Prop->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00007301 continue;
David Blaikie262bc182012-04-30 02:36:29 +00007302 if (!Prop->getPropertyIvarDecl())
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00007303 continue;
David Blaikie262bc182012-04-30 02:36:29 +00007304 ObjCPropertyDecl *PD = Prop->getPropertyDecl();
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00007305 if (!PD)
7306 continue;
7307 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
Fariborz Jahanian301e2e42012-05-03 22:52:13 +00007308 if (mustSynthesizeSetterGetterMethod(IDecl, PD, true /*getter*/))
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00007309 InstanceMethods.push_back(Getter);
7310 if (PD->isReadOnly())
7311 continue;
7312 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
Fariborz Jahanian301e2e42012-05-03 22:52:13 +00007313 if (mustSynthesizeSetterGetterMethod(IDecl, PD, false /*setter*/))
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00007314 InstanceMethods.push_back(Setter);
7315 }
7316
7317 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
7318 "_OBJC_$_INSTANCE_METHODS_",
7319 IDecl->getNameAsString(), true);
7320
7321 SmallVector<ObjCMethodDecl *, 32>
7322 ClassMethods(IDecl->classmeth_begin(), IDecl->classmeth_end());
7323
7324 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
7325 "_OBJC_$_CLASS_METHODS_",
7326 IDecl->getNameAsString(), true);
Fariborz Jahanian0a525342012-02-14 19:31:35 +00007327
7328 // Protocols referenced in class declaration?
7329 // Protocol's super protocol list
7330 std::vector<ObjCProtocolDecl *> RefedProtocols;
7331 const ObjCList<ObjCProtocolDecl> &Protocols = CDecl->getReferencedProtocols();
7332 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
7333 E = Protocols.end();
7334 I != E; ++I) {
7335 RefedProtocols.push_back(*I);
7336 // Must write out all protocol definitions in current qualifier list,
7337 // and in their nested qualifiers before writing out current definition.
7338 RewriteObjCProtocolMetaData(*I, Result);
7339 }
7340
7341 Write_protocol_list_initializer(Context, Result,
7342 RefedProtocols,
7343 "_OBJC_CLASS_PROTOCOLS_$_",
7344 IDecl->getNameAsString());
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00007345
7346 // Protocol's property metadata.
7347 std::vector<ObjCPropertyDecl *> ClassProperties;
7348 for (ObjCContainerDecl::prop_iterator I = CDecl->prop_begin(),
7349 E = CDecl->prop_end(); I != E; ++I)
David Blaikie581deb32012-06-06 20:45:41 +00007350 ClassProperties.push_back(*I);
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00007351
7352 Write_prop_list_t_initializer(*this, Context, Result, ClassProperties,
Fariborz Jahanian2df089d2012-03-22 17:39:35 +00007353 /* Container */IDecl,
Fariborz Jahanianeeabf382012-02-16 21:57:59 +00007354 "_OBJC_$_PROP_LIST_",
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00007355 CDecl->getNameAsString());
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00007356
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00007357
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00007358 // Data for initializing _class_ro_t metaclass meta-data
7359 uint32_t flags = CLS_META;
7360 std::string InstanceSize;
7361 std::string InstanceStart;
7362
7363
7364 bool classIsHidden = CDecl->getVisibility() == HiddenVisibility;
7365 if (classIsHidden)
7366 flags |= OBJC2_CLS_HIDDEN;
7367
7368 if (!CDecl->getSuperClass())
7369 // class is root
7370 flags |= CLS_ROOT;
7371 InstanceSize = "sizeof(struct _class_t)";
7372 InstanceStart = InstanceSize;
7373 Write__class_ro_t_initializer(Context, Result, flags,
7374 InstanceStart, InstanceSize,
7375 ClassMethods,
7376 0,
7377 0,
7378 0,
7379 "_OBJC_METACLASS_RO_$_",
7380 CDecl->getNameAsString());
7381
7382
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00007383 // Data for initializing _class_ro_t meta-data
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00007384 flags = CLS;
7385 if (classIsHidden)
7386 flags |= OBJC2_CLS_HIDDEN;
7387
7388 if (hasObjCExceptionAttribute(*Context, CDecl))
7389 flags |= CLS_EXCEPTION;
7390
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00007391 if (!CDecl->getSuperClass())
7392 // class is root
7393 flags |= CLS_ROOT;
7394
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00007395 InstanceSize.clear();
7396 InstanceStart.clear();
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00007397 if (!ObjCSynthesizedStructs.count(CDecl)) {
7398 InstanceSize = "0";
7399 InstanceStart = "0";
7400 }
7401 else {
7402 InstanceSize = "sizeof(struct ";
7403 InstanceSize += CDecl->getNameAsString();
7404 InstanceSize += "_IMPL)";
7405
7406 ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
7407 if (IVD) {
Fariborz Jahanianacee1c92012-04-11 21:12:36 +00007408 RewriteIvarOffsetComputation(IVD, InstanceStart);
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00007409 }
7410 else
7411 InstanceStart = InstanceSize;
7412 }
7413 Write__class_ro_t_initializer(Context, Result, flags,
7414 InstanceStart, InstanceSize,
7415 InstanceMethods,
7416 RefedProtocols,
7417 IVars,
7418 ClassProperties,
7419 "_OBJC_CLASS_RO_$_",
7420 CDecl->getNameAsString());
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00007421
7422 Write_class_t(Context, Result,
7423 "OBJC_METACLASS_$_",
7424 CDecl, /*metaclass*/true);
7425
7426 Write_class_t(Context, Result,
7427 "OBJC_CLASS_$_",
7428 CDecl, /*metaclass*/false);
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00007429
7430 if (ImplementationIsNonLazy(IDecl))
7431 DefinedNonLazyClasses.push_back(CDecl);
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00007432
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007433}
7434
Fariborz Jahaniane0335782012-03-27 18:41:05 +00007435void RewriteModernObjC::RewriteClassSetupInitHook(std::string &Result) {
7436 int ClsDefCount = ClassImplementation.size();
7437 if (!ClsDefCount)
7438 return;
7439 Result += "#pragma section(\".objc_inithooks$B\", long, read, write)\n";
7440 Result += "__declspec(allocate(\".objc_inithooks$B\")) ";
7441 Result += "static void *OBJC_CLASS_SETUP[] = {\n";
7442 for (int i = 0; i < ClsDefCount; i++) {
7443 ObjCImplementationDecl *IDecl = ClassImplementation[i];
7444 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
7445 Result += "\t(void *)&OBJC_CLASS_SETUP_$_";
7446 Result += CDecl->getName(); Result += ",\n";
7447 }
7448 Result += "};\n";
7449}
7450
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007451void RewriteModernObjC::RewriteMetaDataIntoBuffer(std::string &Result) {
7452 int ClsDefCount = ClassImplementation.size();
7453 int CatDefCount = CategoryImplementation.size();
7454
7455 // For each implemented class, write out all its meta data.
7456 for (int i = 0; i < ClsDefCount; i++)
7457 RewriteObjCClassMetaData(ClassImplementation[i], Result);
7458
Fariborz Jahaniane0335782012-03-27 18:41:05 +00007459 RewriteClassSetupInitHook(Result);
7460
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007461 // For each implemented category, write out all its meta data.
7462 for (int i = 0; i < CatDefCount; i++)
7463 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
7464
Fariborz Jahaniane0335782012-03-27 18:41:05 +00007465 RewriteCategorySetupInitHook(Result);
7466
Fariborz Jahaniandf795672012-02-17 00:06:14 +00007467 if (ClsDefCount > 0) {
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00007468 if (LangOpts.MicrosoftExt)
7469 Result += "__declspec(allocate(\".objc_classlist$B\")) ";
Fariborz Jahaniandf795672012-02-17 00:06:14 +00007470 Result += "static struct _class_t *L_OBJC_LABEL_CLASS_$ [";
7471 Result += llvm::utostr(ClsDefCount); Result += "]";
7472 Result +=
7473 " __attribute__((used, section (\"__DATA, __objc_classlist,"
7474 "regular,no_dead_strip\")))= {\n";
7475 for (int i = 0; i < ClsDefCount; i++) {
7476 Result += "\t&OBJC_CLASS_$_";
7477 Result += ClassImplementation[i]->getNameAsString();
7478 Result += ",\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007479 }
Fariborz Jahaniandf795672012-02-17 00:06:14 +00007480 Result += "};\n";
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00007481
7482 if (!DefinedNonLazyClasses.empty()) {
7483 if (LangOpts.MicrosoftExt)
7484 Result += "__declspec(allocate(\".objc_nlclslist$B\")) \n";
7485 Result += "static struct _class_t *_OBJC_LABEL_NONLAZY_CLASS_$[] = {\n\t";
7486 for (unsigned i = 0, e = DefinedNonLazyClasses.size(); i < e; i++) {
7487 Result += "\t&OBJC_CLASS_$_"; Result += DefinedNonLazyClasses[i]->getNameAsString();
7488 Result += ",\n";
7489 }
7490 Result += "};\n";
7491 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007492 }
Fariborz Jahanian61186122012-02-17 18:40:41 +00007493
7494 if (CatDefCount > 0) {
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00007495 if (LangOpts.MicrosoftExt)
7496 Result += "__declspec(allocate(\".objc_catlist$B\")) ";
Fariborz Jahanian61186122012-02-17 18:40:41 +00007497 Result += "static struct _category_t *L_OBJC_LABEL_CATEGORY_$ [";
7498 Result += llvm::utostr(CatDefCount); Result += "]";
7499 Result +=
7500 " __attribute__((used, section (\"__DATA, __objc_catlist,"
7501 "regular,no_dead_strip\")))= {\n";
7502 for (int i = 0; i < CatDefCount; i++) {
7503 Result += "\t&_OBJC_$_CATEGORY_";
7504 Result +=
7505 CategoryImplementation[i]->getClassInterface()->getNameAsString();
7506 Result += "_$_";
7507 Result += CategoryImplementation[i]->getNameAsString();
7508 Result += ",\n";
7509 }
7510 Result += "};\n";
7511 }
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00007512
7513 if (!DefinedNonLazyCategories.empty()) {
7514 if (LangOpts.MicrosoftExt)
7515 Result += "__declspec(allocate(\".objc_nlcatlist$B\")) \n";
7516 Result += "static struct _category_t *_OBJC_LABEL_NONLAZY_CATEGORY_$[] = {\n\t";
7517 for (unsigned i = 0, e = DefinedNonLazyCategories.size(); i < e; i++) {
7518 Result += "\t&_OBJC_$_CATEGORY_";
7519 Result +=
7520 DefinedNonLazyCategories[i]->getClassInterface()->getNameAsString();
7521 Result += "_$_";
7522 Result += DefinedNonLazyCategories[i]->getNameAsString();
7523 Result += ",\n";
7524 }
7525 Result += "};\n";
7526 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007527}
7528
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00007529void RewriteModernObjC::WriteImageInfo(std::string &Result) {
7530 if (LangOpts.MicrosoftExt)
7531 Result += "__declspec(allocate(\".objc_imageinfo$B\")) \n";
7532
7533 Result += "static struct IMAGE_INFO { unsigned version; unsigned flag; } ";
7534 // version 0, ObjCABI is 2
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00007535 Result += "_OBJC_IMAGE_INFO = { 0, 2 };\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00007536}
7537
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007538/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
7539/// implementation.
7540void RewriteModernObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
7541 std::string &Result) {
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00007542 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007543 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
7544 // Find category declaration for this implementation.
Douglas Gregord3297242013-01-16 23:00:23 +00007545 ObjCCategoryDecl *CDecl
7546 = ClassDecl->FindCategoryDeclaration(IDecl->getIdentifier());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007547
7548 std::string FullCategoryName = ClassDecl->getNameAsString();
Fariborz Jahanian61186122012-02-17 18:40:41 +00007549 FullCategoryName += "_$_";
7550 FullCategoryName += CDecl->getNameAsString();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007551
7552 // Build _objc_method_list for class's instance methods if needed
7553 SmallVector<ObjCMethodDecl *, 32>
7554 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
7555
7556 // If any of our property implementations have associated getters or
7557 // setters, produce metadata for them as well.
7558 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
7559 PropEnd = IDecl->propimpl_end();
7560 Prop != PropEnd; ++Prop) {
David Blaikie262bc182012-04-30 02:36:29 +00007561 if (Prop->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007562 continue;
David Blaikie262bc182012-04-30 02:36:29 +00007563 if (!Prop->getPropertyIvarDecl())
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007564 continue;
David Blaikie262bc182012-04-30 02:36:29 +00007565 ObjCPropertyDecl *PD = Prop->getPropertyDecl();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007566 if (!PD)
7567 continue;
7568 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
7569 InstanceMethods.push_back(Getter);
7570 if (PD->isReadOnly())
7571 continue;
7572 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
7573 InstanceMethods.push_back(Setter);
7574 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007575
Fariborz Jahanian61186122012-02-17 18:40:41 +00007576 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
7577 "_OBJC_$_CATEGORY_INSTANCE_METHODS_",
7578 FullCategoryName, true);
7579
7580 SmallVector<ObjCMethodDecl *, 32>
7581 ClassMethods(IDecl->classmeth_begin(), IDecl->classmeth_end());
7582
7583 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
7584 "_OBJC_$_CATEGORY_CLASS_METHODS_",
7585 FullCategoryName, true);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007586
7587 // Protocols referenced in class declaration?
Fariborz Jahanian61186122012-02-17 18:40:41 +00007588 // Protocol's super protocol list
7589 std::vector<ObjCProtocolDecl *> RefedProtocols;
Argyrios Kyrtzidisa5f44412012-03-13 01:09:41 +00007590 for (ObjCInterfaceDecl::protocol_iterator I = CDecl->protocol_begin(),
7591 E = CDecl->protocol_end();
7592
7593 I != E; ++I) {
Fariborz Jahanian61186122012-02-17 18:40:41 +00007594 RefedProtocols.push_back(*I);
7595 // Must write out all protocol definitions in current qualifier list,
7596 // and in their nested qualifiers before writing out current definition.
7597 RewriteObjCProtocolMetaData(*I, Result);
7598 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007599
Fariborz Jahanian61186122012-02-17 18:40:41 +00007600 Write_protocol_list_initializer(Context, Result,
7601 RefedProtocols,
7602 "_OBJC_CATEGORY_PROTOCOLS_$_",
7603 FullCategoryName);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007604
Fariborz Jahanian61186122012-02-17 18:40:41 +00007605 // Protocol's property metadata.
7606 std::vector<ObjCPropertyDecl *> ClassProperties;
7607 for (ObjCContainerDecl::prop_iterator I = CDecl->prop_begin(),
7608 E = CDecl->prop_end(); I != E; ++I)
David Blaikie581deb32012-06-06 20:45:41 +00007609 ClassProperties.push_back(*I);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007610
Fariborz Jahanian61186122012-02-17 18:40:41 +00007611 Write_prop_list_t_initializer(*this, Context, Result, ClassProperties,
Fariborz Jahanianebfa2722012-05-03 23:19:33 +00007612 /* Container */IDecl,
Fariborz Jahanian61186122012-02-17 18:40:41 +00007613 "_OBJC_$_PROP_LIST_",
7614 FullCategoryName);
7615
7616 Write_category_t(*this, Context, Result,
Fariborz Jahaniane0335782012-03-27 18:41:05 +00007617 CDecl,
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00007618 ClassDecl,
Fariborz Jahanian61186122012-02-17 18:40:41 +00007619 InstanceMethods,
7620 ClassMethods,
7621 RefedProtocols,
7622 ClassProperties);
7623
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00007624 // Determine if this category is also "non-lazy".
7625 if (ImplementationIsNonLazy(IDecl))
7626 DefinedNonLazyCategories.push_back(CDecl);
Fariborz Jahaniane0335782012-03-27 18:41:05 +00007627
7628}
7629
7630void RewriteModernObjC::RewriteCategorySetupInitHook(std::string &Result) {
7631 int CatDefCount = CategoryImplementation.size();
7632 if (!CatDefCount)
7633 return;
7634 Result += "#pragma section(\".objc_inithooks$B\", long, read, write)\n";
7635 Result += "__declspec(allocate(\".objc_inithooks$B\")) ";
7636 Result += "static void *OBJC_CATEGORY_SETUP[] = {\n";
7637 for (int i = 0; i < CatDefCount; i++) {
7638 ObjCCategoryImplDecl *IDecl = CategoryImplementation[i];
7639 ObjCCategoryDecl *CatDecl= IDecl->getCategoryDecl();
7640 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
7641 Result += "\t(void *)&OBJC_CATEGORY_SETUP_$_";
7642 Result += ClassDecl->getName();
7643 Result += "_$_";
7644 Result += CatDecl->getName();
7645 Result += ",\n";
7646 }
7647 Result += "};\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007648}
7649
7650// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
7651/// class methods.
7652template<typename MethodIterator>
7653void RewriteModernObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
7654 MethodIterator MethodEnd,
7655 bool IsInstanceMethod,
7656 StringRef prefix,
7657 StringRef ClassName,
7658 std::string &Result) {
7659 if (MethodBegin == MethodEnd) return;
7660
7661 if (!objc_impl_method) {
7662 /* struct _objc_method {
7663 SEL _cmd;
7664 char *method_types;
7665 void *_imp;
7666 }
7667 */
7668 Result += "\nstruct _objc_method {\n";
7669 Result += "\tSEL _cmd;\n";
7670 Result += "\tchar *method_types;\n";
7671 Result += "\tvoid *_imp;\n";
7672 Result += "};\n";
7673
7674 objc_impl_method = true;
7675 }
7676
7677 // Build _objc_method_list for class's methods if needed
7678
7679 /* struct {
7680 struct _objc_method_list *next_method;
7681 int method_count;
7682 struct _objc_method method_list[];
7683 }
7684 */
7685 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00007686 Result += "\n";
7687 if (LangOpts.MicrosoftExt) {
7688 if (IsInstanceMethod)
7689 Result += "__declspec(allocate(\".inst_meth$B\")) ";
7690 else
7691 Result += "__declspec(allocate(\".cls_meth$B\")) ";
7692 }
7693 Result += "static struct {\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007694 Result += "\tstruct _objc_method_list *next_method;\n";
7695 Result += "\tint method_count;\n";
7696 Result += "\tstruct _objc_method method_list[";
7697 Result += utostr(NumMethods);
7698 Result += "];\n} _OBJC_";
7699 Result += prefix;
7700 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
7701 Result += "_METHODS_";
7702 Result += ClassName;
7703 Result += " __attribute__ ((used, section (\"__OBJC, __";
7704 Result += IsInstanceMethod ? "inst" : "cls";
7705 Result += "_meth\")))= ";
7706 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
7707
7708 Result += "\t,{{(SEL)\"";
7709 Result += (*MethodBegin)->getSelector().getAsString().c_str();
7710 std::string MethodTypeString;
7711 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
7712 Result += "\", \"";
7713 Result += MethodTypeString;
7714 Result += "\", (void *)";
7715 Result += MethodInternalNames[*MethodBegin];
7716 Result += "}\n";
7717 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
7718 Result += "\t ,{(SEL)\"";
7719 Result += (*MethodBegin)->getSelector().getAsString().c_str();
7720 std::string MethodTypeString;
7721 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
7722 Result += "\", \"";
7723 Result += MethodTypeString;
7724 Result += "\", (void *)";
7725 Result += MethodInternalNames[*MethodBegin];
7726 Result += "}\n";
7727 }
7728 Result += "\t }\n};\n";
7729}
7730
7731Stmt *RewriteModernObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) {
7732 SourceRange OldRange = IV->getSourceRange();
7733 Expr *BaseExpr = IV->getBase();
7734
7735 // Rewrite the base, but without actually doing replaces.
7736 {
7737 DisableReplaceStmtScope S(*this);
7738 BaseExpr = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(BaseExpr));
7739 IV->setBase(BaseExpr);
7740 }
7741
7742 ObjCIvarDecl *D = IV->getDecl();
7743
7744 Expr *Replacement = IV;
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007745
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007746 if (BaseExpr->getType()->isObjCObjectPointerType()) {
7747 const ObjCInterfaceType *iFaceDecl =
Fariborz Jahanian163d3ce2012-05-08 23:54:35 +00007748 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007749 assert(iFaceDecl && "RewriteObjCIvarRefExpr - iFaceDecl is null");
7750 // lookup which class implements the instance variable.
7751 ObjCInterfaceDecl *clsDeclared = 0;
7752 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
7753 clsDeclared);
7754 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
7755
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007756 // Build name of symbol holding ivar offset.
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00007757 std::string IvarOffsetName;
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00007758 if (D->isBitField())
7759 ObjCIvarBitfieldGroupOffset(D, IvarOffsetName);
7760 else
7761 WriteInternalIvarName(clsDeclared, D, IvarOffsetName);
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00007762
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00007763 ReferencedIvars[clsDeclared].insert(D);
7764
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007765 // cast offset to "char *".
7766 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context,
7767 Context->getPointerType(Context->CharTy),
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007768 CK_BitCast,
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007769 BaseExpr);
7770 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
7771 SourceLocation(), &Context->Idents.get(IvarOffsetName),
7772 Context->UnsignedLongTy, 0, SC_Extern, SC_None);
John McCallf4b88a42012-03-10 09:33:50 +00007773 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, false,
7774 Context->UnsignedLongTy, VK_LValue,
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007775 SourceLocation());
7776 BinaryOperator *addExpr =
7777 new (Context) BinaryOperator(castExpr, DRE, BO_Add,
7778 Context->getPointerType(Context->CharTy),
Lang Hamesbe9af122012-10-02 04:45:10 +00007779 VK_RValue, OK_Ordinary, SourceLocation(), false);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007780 // Don't forget the parens to enforce the proper binding.
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007781 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(),
7782 SourceLocation(),
7783 addExpr);
Fariborz Jahanian0d6e22a2012-02-24 17:35:35 +00007784 QualType IvarT = D->getType();
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00007785 if (D->isBitField())
7786 IvarT = GetGroupRecordTypeForObjCIvarBitfield(D);
Fariborz Jahanian27fc81b2012-04-27 22:48:54 +00007787
Fariborz Jahanianf5eac482012-05-02 17:34:59 +00007788 if (!isa<TypedefType>(IvarT) && IvarT->isRecordType()) {
Fariborz Jahanian27fc81b2012-04-27 22:48:54 +00007789 RecordDecl *RD = IvarT->getAs<RecordType>()->getDecl();
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00007790 RD = RD->getDefinition();
7791 if (RD && !RD->getDeclName().getAsIdentifierInfo()) {
Fariborz Jahanian27fc81b2012-04-27 22:48:54 +00007792 // decltype(((Foo_IMPL*)0)->bar) *
Fariborz Jahanianf5eac482012-05-02 17:34:59 +00007793 ObjCContainerDecl *CDecl =
7794 dyn_cast<ObjCContainerDecl>(D->getDeclContext());
7795 // ivar in class extensions requires special treatment.
7796 if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(CDecl))
7797 CDecl = CatDecl->getClassInterface();
7798 std::string RecName = CDecl->getName();
Fariborz Jahanian27fc81b2012-04-27 22:48:54 +00007799 RecName += "_IMPL";
7800 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
7801 SourceLocation(), SourceLocation(),
7802 &Context->Idents.get(RecName.c_str()));
7803 QualType PtrStructIMPL = Context->getPointerType(Context->getTagDeclType(RD));
7804 unsigned UnsignedIntSize =
7805 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
7806 Expr *Zero = IntegerLiteral::Create(*Context,
7807 llvm::APInt(UnsignedIntSize, 0),
7808 Context->UnsignedIntTy, SourceLocation());
7809 Zero = NoTypeInfoCStyleCastExpr(Context, PtrStructIMPL, CK_BitCast, Zero);
7810 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
7811 Zero);
7812 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
7813 SourceLocation(),
7814 &Context->Idents.get(D->getNameAsString()),
7815 IvarT, 0,
7816 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smithca523302012-06-10 03:12:00 +00007817 ICIS_NoInit);
Fariborz Jahanian27fc81b2012-04-27 22:48:54 +00007818 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
7819 FD->getType(), VK_LValue,
7820 OK_Ordinary);
7821 IvarT = Context->getDecltypeType(ME, ME->getType());
7822 }
7823 }
Fariborz Jahanian8e0913d2012-02-29 00:26:20 +00007824 convertObjCTypeToCStyleType(IvarT);
Fariborz Jahanian0d6e22a2012-02-24 17:35:35 +00007825 QualType castT = Context->getPointerType(IvarT);
Fariborz Jahanian27fc81b2012-04-27 22:48:54 +00007826
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007827 castExpr = NoTypeInfoCStyleCastExpr(Context,
7828 castT,
7829 CK_BitCast,
7830 PE);
Fariborz Jahanian27fc81b2012-04-27 22:48:54 +00007831
7832
Fariborz Jahanian8e0913d2012-02-29 00:26:20 +00007833 Expr *Exp = new (Context) UnaryOperator(castExpr, UO_Deref, IvarT,
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007834 VK_LValue, OK_Ordinary,
7835 SourceLocation());
7836 PE = new (Context) ParenExpr(OldRange.getBegin(),
7837 OldRange.getEnd(),
7838 Exp);
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00007839
7840 if (D->isBitField()) {
7841 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
7842 SourceLocation(),
7843 &Context->Idents.get(D->getNameAsString()),
7844 D->getType(), 0,
7845 /*BitWidth=*/D->getBitWidth(),
7846 /*Mutable=*/true,
7847 ICIS_NoInit);
7848 MemberExpr *ME = new (Context) MemberExpr(PE, /*isArrow*/false, FD, SourceLocation(),
7849 FD->getType(), VK_LValue,
7850 OK_Ordinary);
7851 Replacement = ME;
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007852
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00007853 }
7854 else
7855 Replacement = PE;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007856 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007857
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007858 ReplaceStmtWithRange(IV, Replacement, OldRange);
7859 return Replacement;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007860}