blob: 580d396bb459a4f051a5237638e965b079f7d16f [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
14#include "clang/Rewrite/ASTConsumers.h"
15#include "clang/Rewrite/Rewriter.h"
16#include "clang/AST/AST.h"
17#include "clang/AST/ASTConsumer.h"
18#include "clang/AST/ParentMap.h"
19#include "clang/Basic/SourceManager.h"
20#include "clang/Basic/IdentifierTable.h"
21#include "clang/Basic/Diagnostic.h"
22#include "clang/Lex/Lexer.h"
23#include "llvm/Support/MemoryBuffer.h"
24#include "llvm/Support/raw_ostream.h"
25#include "llvm/ADT/StringExtras.h"
26#include "llvm/ADT/SmallPtrSet.h"
27#include "llvm/ADT/OwningPtr.h"
28#include "llvm/ADT/DenseSet.h"
29
30using namespace clang;
31using llvm::utostr;
32
33namespace {
34 class RewriteModernObjC : public ASTConsumer {
35 protected:
36
37 enum {
38 BLOCK_FIELD_IS_OBJECT = 3, /* id, NSObject, __attribute__((NSObject)),
39 block, ... */
40 BLOCK_FIELD_IS_BLOCK = 7, /* a block variable */
41 BLOCK_FIELD_IS_BYREF = 8, /* the on stack structure holding the
42 __block variable */
43 BLOCK_FIELD_IS_WEAK = 16, /* declared __weak, only used in byref copy
44 helpers */
45 BLOCK_BYREF_CALLER = 128, /* called from __block (byref) copy/dispose
46 support routines */
47 BLOCK_BYREF_CURRENT_MAX = 256
48 };
49
50 enum {
51 BLOCK_NEEDS_FREE = (1 << 24),
52 BLOCK_HAS_COPY_DISPOSE = (1 << 25),
53 BLOCK_HAS_CXX_OBJ = (1 << 26),
54 BLOCK_IS_GC = (1 << 27),
55 BLOCK_IS_GLOBAL = (1 << 28),
56 BLOCK_HAS_DESCRIPTOR = (1 << 29)
57 };
58 static const int OBJC_ABI_VERSION = 7;
59
60 Rewriter Rewrite;
61 DiagnosticsEngine &Diags;
62 const LangOptions &LangOpts;
63 ASTContext *Context;
64 SourceManager *SM;
65 TranslationUnitDecl *TUDecl;
66 FileID MainFileID;
67 const char *MainFileStart, *MainFileEnd;
68 Stmt *CurrentBody;
69 ParentMap *PropParentMap; // created lazily.
70 std::string InFileName;
71 raw_ostream* OutFile;
72 std::string Preamble;
73
74 TypeDecl *ProtocolTypeDecl;
75 VarDecl *GlobalVarDecl;
76 unsigned RewriteFailedDiag;
77 // ObjC string constant support.
78 unsigned NumObjCStringLiterals;
79 VarDecl *ConstantStringClassReference;
80 RecordDecl *NSStringRecord;
81
82 // ObjC foreach break/continue generation support.
83 int BcLabelCount;
84
85 unsigned TryFinallyContainsReturnDiag;
86 // Needed for super.
87 ObjCMethodDecl *CurMethodDef;
88 RecordDecl *SuperStructDecl;
89 RecordDecl *ConstantStringDecl;
90
91 FunctionDecl *MsgSendFunctionDecl;
92 FunctionDecl *MsgSendSuperFunctionDecl;
93 FunctionDecl *MsgSendStretFunctionDecl;
94 FunctionDecl *MsgSendSuperStretFunctionDecl;
95 FunctionDecl *MsgSendFpretFunctionDecl;
96 FunctionDecl *GetClassFunctionDecl;
97 FunctionDecl *GetMetaClassFunctionDecl;
98 FunctionDecl *GetSuperClassFunctionDecl;
99 FunctionDecl *SelGetUidFunctionDecl;
100 FunctionDecl *CFStringFunctionDecl;
101 FunctionDecl *SuperContructorFunctionDecl;
102 FunctionDecl *CurFunctionDef;
103 FunctionDecl *CurFunctionDeclToDeclareForBlock;
104
105 /* Misc. containers needed for meta-data rewrite. */
106 SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
107 SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
108 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs;
109 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> ObjCSynthesizedProtocols;
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +0000110 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCWrittenInterfaces;
Fariborz Jahanian15f87772012-02-28 22:45:07 +0000111 llvm::SmallPtrSet<TagDecl*, 8> TagsDefinedInIvarDecls;
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +0000112 SmallVector<ObjCInterfaceDecl*, 32> ObjCInterfacesSeen;
Fariborz Jahanian88f7f752012-03-14 23:18:19 +0000113 /// DefinedNonLazyClasses - List of defined "non-lazy" classes.
114 SmallVector<ObjCInterfaceDecl*, 8> DefinedNonLazyClasses;
115
116 /// DefinedNonLazyCategories - List of defined "non-lazy" categories.
117 llvm::SmallVector<ObjCCategoryDecl*, 8> DefinedNonLazyCategories;
118
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000119 SmallVector<Stmt *, 32> Stmts;
120 SmallVector<int, 8> ObjCBcLabelNo;
121 // Remember all the @protocol(<expr>) expressions.
122 llvm::SmallPtrSet<ObjCProtocolDecl *, 32> ProtocolExprDecls;
123
124 llvm::DenseSet<uint64_t> CopyDestroyCache;
125
126 // Block expressions.
127 SmallVector<BlockExpr *, 32> Blocks;
128 SmallVector<int, 32> InnerDeclRefsCount;
John McCallf4b88a42012-03-10 09:33:50 +0000129 SmallVector<DeclRefExpr *, 32> InnerDeclRefs;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000130
John McCallf4b88a42012-03-10 09:33:50 +0000131 SmallVector<DeclRefExpr *, 32> BlockDeclRefs;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000132
133 // Block related declarations.
134 SmallVector<ValueDecl *, 8> BlockByCopyDecls;
135 llvm::SmallPtrSet<ValueDecl *, 8> BlockByCopyDeclsPtrSet;
136 SmallVector<ValueDecl *, 8> BlockByRefDecls;
137 llvm::SmallPtrSet<ValueDecl *, 8> BlockByRefDeclsPtrSet;
138 llvm::DenseMap<ValueDecl *, unsigned> BlockByRefDeclNo;
139 llvm::SmallPtrSet<ValueDecl *, 8> ImportedBlockDecls;
140 llvm::SmallPtrSet<VarDecl *, 8> ImportedLocalExternalDecls;
141
142 llvm::DenseMap<BlockExpr *, std::string> RewrittenBlockExprs;
Fariborz Jahanian72c88f12012-02-22 18:13:25 +0000143 llvm::DenseMap<ObjCInterfaceDecl *,
144 llvm::SmallPtrSet<ObjCIvarDecl *, 8> > ReferencedIvars;
145
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000146 // This maps an original source AST to it's rewritten form. This allows
147 // us to avoid rewriting the same node twice (which is very uncommon).
148 // This is needed to support some of the exotic property rewriting.
149 llvm::DenseMap<Stmt *, Stmt *> ReplacedNodes;
150
151 // Needed for header files being rewritten
152 bool IsHeader;
153 bool SilenceRewriteMacroWarning;
154 bool objc_impl_method;
155
156 bool DisableReplaceStmt;
157 class DisableReplaceStmtScope {
158 RewriteModernObjC &R;
159 bool SavedValue;
160
161 public:
162 DisableReplaceStmtScope(RewriteModernObjC &R)
163 : R(R), SavedValue(R.DisableReplaceStmt) {
164 R.DisableReplaceStmt = true;
165 }
166 ~DisableReplaceStmtScope() {
167 R.DisableReplaceStmt = SavedValue;
168 }
169 };
170 void InitializeCommon(ASTContext &context);
171
172 public:
Fariborz Jahanian90af4e22012-02-14 17:19:02 +0000173 llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000174 // Top Level Driver code.
175 virtual bool HandleTopLevelDecl(DeclGroupRef D) {
176 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
177 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(*I)) {
178 if (!Class->isThisDeclarationADefinition()) {
179 RewriteForwardClassDecl(D);
180 break;
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +0000181 } else {
182 // Keep track of all interface declarations seen.
Fariborz Jahanianf3295272012-02-24 21:42:38 +0000183 ObjCInterfacesSeen.push_back(Class);
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +0000184 break;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000185 }
186 }
187
188 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>(*I)) {
189 if (!Proto->isThisDeclarationADefinition()) {
190 RewriteForwardProtocolDecl(D);
191 break;
192 }
193 }
194
195 HandleTopLevelSingleDecl(*I);
196 }
197 return true;
198 }
199 void HandleTopLevelSingleDecl(Decl *D);
200 void HandleDeclInMainFile(Decl *D);
201 RewriteModernObjC(std::string inFile, raw_ostream *OS,
202 DiagnosticsEngine &D, const LangOptions &LOpts,
203 bool silenceMacroWarn);
204
205 ~RewriteModernObjC() {}
206
207 virtual void HandleTranslationUnit(ASTContext &C);
208
209 void ReplaceStmt(Stmt *Old, Stmt *New) {
210 Stmt *ReplacingStmt = ReplacedNodes[Old];
211
212 if (ReplacingStmt)
213 return; // We can't rewrite the same node twice.
214
215 if (DisableReplaceStmt)
216 return;
217
218 // If replacement succeeded or warning disabled return with no warning.
219 if (!Rewrite.ReplaceStmt(Old, New)) {
220 ReplacedNodes[Old] = New;
221 return;
222 }
223 if (SilenceRewriteMacroWarning)
224 return;
225 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
226 << Old->getSourceRange();
227 }
228
229 void ReplaceStmtWithRange(Stmt *Old, Stmt *New, SourceRange SrcRange) {
230 if (DisableReplaceStmt)
231 return;
232
233 // Measure the old text.
234 int Size = Rewrite.getRangeSize(SrcRange);
235 if (Size == -1) {
236 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
237 << Old->getSourceRange();
238 return;
239 }
240 // Get the new text.
241 std::string SStr;
242 llvm::raw_string_ostream S(SStr);
243 New->printPretty(S, *Context, 0, PrintingPolicy(LangOpts));
244 const std::string &Str = S.str();
245
246 // If replacement succeeded or warning disabled return with no warning.
247 if (!Rewrite.ReplaceText(SrcRange.getBegin(), Size, Str)) {
248 ReplacedNodes[Old] = New;
249 return;
250 }
251 if (SilenceRewriteMacroWarning)
252 return;
253 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
254 << Old->getSourceRange();
255 }
256
257 void InsertText(SourceLocation Loc, StringRef Str,
258 bool InsertAfter = true) {
259 // If insertion succeeded or warning disabled return with no warning.
260 if (!Rewrite.InsertText(Loc, Str, InsertAfter) ||
261 SilenceRewriteMacroWarning)
262 return;
263
264 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
265 }
266
267 void ReplaceText(SourceLocation Start, unsigned OrigLength,
268 StringRef Str) {
269 // If removal succeeded or warning disabled return with no warning.
270 if (!Rewrite.ReplaceText(Start, OrigLength, Str) ||
271 SilenceRewriteMacroWarning)
272 return;
273
274 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
275 }
276
277 // Syntactic Rewriting.
278 void RewriteRecordBody(RecordDecl *RD);
279 void RewriteInclude();
280 void RewriteForwardClassDecl(DeclGroupRef D);
281 void RewriteForwardClassDecl(const llvm::SmallVector<Decl*, 8> &DG);
282 void RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
283 const std::string &typedefString);
284 void RewriteImplementations();
285 void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
286 ObjCImplementationDecl *IMD,
287 ObjCCategoryImplDecl *CID);
288 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
289 void RewriteImplementationDecl(Decl *Dcl);
290 void RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
291 ObjCMethodDecl *MDecl, std::string &ResultStr);
292 void RewriteTypeIntoString(QualType T, std::string &ResultStr,
293 const FunctionType *&FPRetType);
294 void RewriteByRefString(std::string &ResultStr, const std::string &Name,
295 ValueDecl *VD, bool def=false);
296 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
297 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
298 void RewriteForwardProtocolDecl(DeclGroupRef D);
299 void RewriteForwardProtocolDecl(const llvm::SmallVector<Decl*, 8> &DG);
300 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
301 void RewriteProperty(ObjCPropertyDecl *prop);
302 void RewriteFunctionDecl(FunctionDecl *FD);
303 void RewriteBlockPointerType(std::string& Str, QualType Type);
304 void RewriteBlockPointerTypeVariable(std::string& Str, ValueDecl *VD);
305 void RewriteBlockLiteralFunctionDecl(FunctionDecl *FD);
306 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
307 void RewriteTypeOfDecl(VarDecl *VD);
308 void RewriteObjCQualifiedInterfaceTypes(Expr *E);
309
310 // Expression Rewriting.
311 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
312 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
313 Stmt *RewritePropertyOrImplicitGetter(PseudoObjectExpr *Pseudo);
314 Stmt *RewritePropertyOrImplicitSetter(PseudoObjectExpr *Pseudo);
315 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
316 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
317 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
318 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
319 void RewriteTryReturnStmts(Stmt *S);
320 void RewriteSyncReturnStmts(Stmt *S, std::string buf);
321 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
322 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
323 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
324 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
325 SourceLocation OrigEnd);
326 Stmt *RewriteBreakStmt(BreakStmt *S);
327 Stmt *RewriteContinueStmt(ContinueStmt *S);
328 void RewriteCastExpr(CStyleCastExpr *CE);
329
330 // Block rewriting.
331 void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D);
332
333 // Block specific rewrite rules.
334 void RewriteBlockPointerDecl(NamedDecl *VD);
335 void RewriteByRefVar(VarDecl *VD);
John McCallf4b88a42012-03-10 09:33:50 +0000336 Stmt *RewriteBlockDeclRefExpr(DeclRefExpr *VD);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000337 Stmt *RewriteLocalVariableExternalStorage(DeclRefExpr *DRE);
338 void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
339
340 void RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
341 std::string &Result);
342
Fariborz Jahanian15f87772012-02-28 22:45:07 +0000343 void RewriteObjCFieldDecl(FieldDecl *fieldDecl, std::string &Result);
344
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +0000345 bool RewriteObjCFieldDeclType(QualType &Type, std::string &Result);
346
Fariborz Jahanian72c88f12012-02-22 18:13:25 +0000347 void RewriteIvarOffsetSymbols(ObjCInterfaceDecl *CDecl,
348 std::string &Result);
349
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000350 virtual void Initialize(ASTContext &context);
351
352 // Misc. AST transformation routines. Somtimes they end up calling
353 // rewriting routines on the new ASTs.
354 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
355 Expr **args, unsigned nargs,
356 SourceLocation StartLoc=SourceLocation(),
357 SourceLocation EndLoc=SourceLocation());
358
359 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp,
360 SourceLocation StartLoc=SourceLocation(),
361 SourceLocation EndLoc=SourceLocation());
362
363 void SynthCountByEnumWithState(std::string &buf);
364 void SynthMsgSendFunctionDecl();
365 void SynthMsgSendSuperFunctionDecl();
366 void SynthMsgSendStretFunctionDecl();
367 void SynthMsgSendFpretFunctionDecl();
368 void SynthMsgSendSuperStretFunctionDecl();
369 void SynthGetClassFunctionDecl();
370 void SynthGetMetaClassFunctionDecl();
371 void SynthGetSuperClassFunctionDecl();
372 void SynthSelGetUidFunctionDecl();
373 void SynthSuperContructorFunctionDecl();
374
375 // Rewriting metadata
376 template<typename MethodIterator>
377 void RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
378 MethodIterator MethodEnd,
379 bool IsInstanceMethod,
380 StringRef prefix,
381 StringRef ClassName,
382 std::string &Result);
Fariborz Jahanianda9624a2012-02-08 19:53:58 +0000383 void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
384 std::string &Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000385 virtual void RewriteObjCProtocolListMetaData(
386 const ObjCList<ObjCProtocolDecl> &Prots,
387 StringRef prefix, StringRef ClassName, std::string &Result);
388 virtual void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
389 std::string &Result);
390 virtual void RewriteMetaDataIntoBuffer(std::string &Result);
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +0000391 virtual void WriteImageInfo(std::string &Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000392 virtual void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
393 std::string &Result);
394
395 // Rewriting ivar
396 virtual void RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
397 std::string &Result);
398 virtual Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV);
399
400
401 std::string SynthesizeByrefCopyDestroyHelper(VarDecl *VD, int flag);
402 std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
403 StringRef funcName, std::string Tag);
404 std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
405 StringRef funcName, std::string Tag);
406 std::string SynthesizeBlockImpl(BlockExpr *CE,
407 std::string Tag, std::string Desc);
408 std::string SynthesizeBlockDescriptor(std::string DescTag,
409 std::string ImplTag,
410 int i, StringRef funcName,
411 unsigned hasCopy);
412 Stmt *SynthesizeBlockCall(CallExpr *Exp, const Expr* BlockExp);
413 void SynthesizeBlockLiterals(SourceLocation FunLocStart,
414 StringRef FunName);
415 FunctionDecl *SynthBlockInitFunctionDecl(StringRef name);
416 Stmt *SynthBlockInitExpr(BlockExpr *Exp,
John McCallf4b88a42012-03-10 09:33:50 +0000417 const SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000418
419 // Misc. helper routines.
420 QualType getProtocolType();
421 void WarnAboutReturnGotoStmts(Stmt *S);
422 void HasReturnStmts(Stmt *S, bool &hasReturns);
423 void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
424 void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
425 void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
426
427 bool IsDeclStmtInForeachHeader(DeclStmt *DS);
428 void CollectBlockDeclRefInfo(BlockExpr *Exp);
429 void GetBlockDeclRefExprs(Stmt *S);
430 void GetInnerBlockDeclRefExprs(Stmt *S,
John McCallf4b88a42012-03-10 09:33:50 +0000431 SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000432 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts);
433
434 // We avoid calling Type::isBlockPointerType(), since it operates on the
435 // canonical type. We only care if the top-level type is a closure pointer.
436 bool isTopLevelBlockPointerType(QualType T) {
437 return isa<BlockPointerType>(T);
438 }
439
440 /// convertBlockPointerToFunctionPointer - Converts a block-pointer type
441 /// to a function pointer type and upon success, returns true; false
442 /// otherwise.
443 bool convertBlockPointerToFunctionPointer(QualType &T) {
444 if (isTopLevelBlockPointerType(T)) {
445 const BlockPointerType *BPT = T->getAs<BlockPointerType>();
446 T = Context->getPointerType(BPT->getPointeeType());
447 return true;
448 }
449 return false;
450 }
451
Fariborz Jahanian164d6f82012-02-13 18:57:49 +0000452 bool convertObjCTypeToCStyleType(QualType &T);
453
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000454 bool needToScanForQualifiers(QualType T);
455 QualType getSuperStructType();
456 QualType getConstantStringStructType();
457 QualType convertFunctionTypeOfBlocks(const FunctionType *FT);
458 bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
459
460 void convertToUnqualifiedObjCType(QualType &T) {
461 if (T->isObjCQualifiedIdType())
462 T = Context->getObjCIdType();
463 else if (T->isObjCQualifiedClassType())
464 T = Context->getObjCClassType();
465 else if (T->isObjCObjectPointerType() &&
466 T->getPointeeType()->isObjCQualifiedInterfaceType()) {
467 if (const ObjCObjectPointerType * OBJPT =
468 T->getAsObjCInterfacePointerType()) {
469 const ObjCInterfaceType *IFaceT = OBJPT->getInterfaceType();
470 T = QualType(IFaceT, 0);
471 T = Context->getPointerType(T);
472 }
473 }
474 }
475
476 // FIXME: This predicate seems like it would be useful to add to ASTContext.
477 bool isObjCType(QualType T) {
478 if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
479 return false;
480
481 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
482
483 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
484 OCT == Context->getCanonicalType(Context->getObjCClassType()))
485 return true;
486
487 if (const PointerType *PT = OCT->getAs<PointerType>()) {
488 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
489 PT->getPointeeType()->isObjCQualifiedIdType())
490 return true;
491 }
492 return false;
493 }
494 bool PointerTypeTakesAnyBlockArguments(QualType QT);
495 bool PointerTypeTakesAnyObjCQualifiedType(QualType QT);
496 void GetExtentOfArgList(const char *Name, const char *&LParen,
497 const char *&RParen);
498
499 void QuoteDoublequotes(std::string &From, std::string &To) {
500 for (unsigned i = 0; i < From.length(); i++) {
501 if (From[i] == '"')
502 To += "\\\"";
503 else
504 To += From[i];
505 }
506 }
507
508 QualType getSimpleFunctionType(QualType result,
509 const QualType *args,
510 unsigned numArgs,
511 bool variadic = false) {
512 if (result == Context->getObjCInstanceType())
513 result = Context->getObjCIdType();
514 FunctionProtoType::ExtProtoInfo fpi;
515 fpi.Variadic = variadic;
516 return Context->getFunctionType(result, args, numArgs, fpi);
517 }
518
519 // Helper function: create a CStyleCastExpr with trivial type source info.
520 CStyleCastExpr* NoTypeInfoCStyleCastExpr(ASTContext *Ctx, QualType Ty,
521 CastKind Kind, Expr *E) {
522 TypeSourceInfo *TInfo = Ctx->getTrivialTypeSourceInfo(Ty, SourceLocation());
523 return CStyleCastExpr::Create(*Ctx, Ty, VK_RValue, Kind, E, 0, TInfo,
524 SourceLocation(), SourceLocation());
525 }
Fariborz Jahanian88f7f752012-03-14 23:18:19 +0000526
527 bool ImplementationIsNonLazy(const ObjCImplDecl *OD) const {
528 IdentifierInfo* II = &Context->Idents.get("load");
529 Selector LoadSel = Context->Selectors.getSelector(0, &II);
530 return OD->getClassMethod(LoadSel) != 0;
531 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000532 };
533
534}
535
536void RewriteModernObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
537 NamedDecl *D) {
538 if (const FunctionProtoType *fproto
539 = dyn_cast<FunctionProtoType>(funcType.IgnoreParens())) {
540 for (FunctionProtoType::arg_type_iterator I = fproto->arg_type_begin(),
541 E = fproto->arg_type_end(); I && (I != E); ++I)
542 if (isTopLevelBlockPointerType(*I)) {
543 // All the args are checked/rewritten. Don't call twice!
544 RewriteBlockPointerDecl(D);
545 break;
546 }
547 }
548}
549
550void RewriteModernObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
551 const PointerType *PT = funcType->getAs<PointerType>();
552 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
553 RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
554}
555
556static bool IsHeaderFile(const std::string &Filename) {
557 std::string::size_type DotPos = Filename.rfind('.');
558
559 if (DotPos == std::string::npos) {
560 // no file extension
561 return false;
562 }
563
564 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
565 // C header: .h
566 // C++ header: .hh or .H;
567 return Ext == "h" || Ext == "hh" || Ext == "H";
568}
569
570RewriteModernObjC::RewriteModernObjC(std::string inFile, raw_ostream* OS,
571 DiagnosticsEngine &D, const LangOptions &LOpts,
572 bool silenceMacroWarn)
573 : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(OS),
574 SilenceRewriteMacroWarning(silenceMacroWarn) {
575 IsHeader = IsHeaderFile(inFile);
576 RewriteFailedDiag = Diags.getCustomDiagID(DiagnosticsEngine::Warning,
577 "rewriting sub-expression within a macro (may not be correct)");
578 TryFinallyContainsReturnDiag = Diags.getCustomDiagID(
579 DiagnosticsEngine::Warning,
580 "rewriter doesn't support user-specified control flow semantics "
581 "for @try/@finally (code may not execute properly)");
582}
583
584ASTConsumer *clang::CreateModernObjCRewriter(const std::string& InFile,
585 raw_ostream* OS,
586 DiagnosticsEngine &Diags,
587 const LangOptions &LOpts,
588 bool SilenceRewriteMacroWarning) {
589 return new RewriteModernObjC(InFile, OS, Diags, LOpts, SilenceRewriteMacroWarning);
590}
591
592void RewriteModernObjC::InitializeCommon(ASTContext &context) {
593 Context = &context;
594 SM = &Context->getSourceManager();
595 TUDecl = Context->getTranslationUnitDecl();
596 MsgSendFunctionDecl = 0;
597 MsgSendSuperFunctionDecl = 0;
598 MsgSendStretFunctionDecl = 0;
599 MsgSendSuperStretFunctionDecl = 0;
600 MsgSendFpretFunctionDecl = 0;
601 GetClassFunctionDecl = 0;
602 GetMetaClassFunctionDecl = 0;
603 GetSuperClassFunctionDecl = 0;
604 SelGetUidFunctionDecl = 0;
605 CFStringFunctionDecl = 0;
606 ConstantStringClassReference = 0;
607 NSStringRecord = 0;
608 CurMethodDef = 0;
609 CurFunctionDef = 0;
610 CurFunctionDeclToDeclareForBlock = 0;
611 GlobalVarDecl = 0;
612 SuperStructDecl = 0;
613 ProtocolTypeDecl = 0;
614 ConstantStringDecl = 0;
615 BcLabelCount = 0;
616 SuperContructorFunctionDecl = 0;
617 NumObjCStringLiterals = 0;
618 PropParentMap = 0;
619 CurrentBody = 0;
620 DisableReplaceStmt = false;
621 objc_impl_method = false;
622
623 // Get the ID and start/end of the main file.
624 MainFileID = SM->getMainFileID();
625 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
626 MainFileStart = MainBuf->getBufferStart();
627 MainFileEnd = MainBuf->getBufferEnd();
628
David Blaikie4e4d0842012-03-11 07:00:24 +0000629 Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOpts());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000630}
631
632//===----------------------------------------------------------------------===//
633// Top Level Driver Code
634//===----------------------------------------------------------------------===//
635
636void RewriteModernObjC::HandleTopLevelSingleDecl(Decl *D) {
637 if (Diags.hasErrorOccurred())
638 return;
639
640 // Two cases: either the decl could be in the main file, or it could be in a
641 // #included file. If the former, rewrite it now. If the later, check to see
642 // if we rewrote the #include/#import.
643 SourceLocation Loc = D->getLocation();
644 Loc = SM->getExpansionLoc(Loc);
645
646 // If this is for a builtin, ignore it.
647 if (Loc.isInvalid()) return;
648
649 // Look for built-in declarations that we need to refer during the rewrite.
650 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
651 RewriteFunctionDecl(FD);
652 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
653 // declared in <Foundation/NSString.h>
654 if (FVD->getName() == "_NSConstantStringClassReference") {
655 ConstantStringClassReference = FVD;
656 return;
657 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000658 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
659 RewriteCategoryDecl(CD);
660 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
661 if (PD->isThisDeclarationADefinition())
662 RewriteProtocolDecl(PD);
663 } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
664 // Recurse into linkage specifications
665 for (DeclContext::decl_iterator DI = LSD->decls_begin(),
666 DIEnd = LSD->decls_end();
667 DI != DIEnd; ) {
668 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>((*DI))) {
669 if (!IFace->isThisDeclarationADefinition()) {
670 SmallVector<Decl *, 8> DG;
671 SourceLocation StartLoc = IFace->getLocStart();
672 do {
673 if (isa<ObjCInterfaceDecl>(*DI) &&
674 !cast<ObjCInterfaceDecl>(*DI)->isThisDeclarationADefinition() &&
675 StartLoc == (*DI)->getLocStart())
676 DG.push_back(*DI);
677 else
678 break;
679
680 ++DI;
681 } while (DI != DIEnd);
682 RewriteForwardClassDecl(DG);
683 continue;
684 }
685 }
686
687 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>((*DI))) {
688 if (!Proto->isThisDeclarationADefinition()) {
689 SmallVector<Decl *, 8> DG;
690 SourceLocation StartLoc = Proto->getLocStart();
691 do {
692 if (isa<ObjCProtocolDecl>(*DI) &&
693 !cast<ObjCProtocolDecl>(*DI)->isThisDeclarationADefinition() &&
694 StartLoc == (*DI)->getLocStart())
695 DG.push_back(*DI);
696 else
697 break;
698
699 ++DI;
700 } while (DI != DIEnd);
701 RewriteForwardProtocolDecl(DG);
702 continue;
703 }
704 }
705
706 HandleTopLevelSingleDecl(*DI);
707 ++DI;
708 }
709 }
710 // If we have a decl in the main file, see if we should rewrite it.
711 if (SM->isFromMainFile(Loc))
712 return HandleDeclInMainFile(D);
713}
714
715//===----------------------------------------------------------------------===//
716// Syntactic (non-AST) Rewriting Code
717//===----------------------------------------------------------------------===//
718
719void RewriteModernObjC::RewriteInclude() {
720 SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
721 StringRef MainBuf = SM->getBufferData(MainFileID);
722 const char *MainBufStart = MainBuf.begin();
723 const char *MainBufEnd = MainBuf.end();
724 size_t ImportLen = strlen("import");
725
726 // Loop over the whole file, looking for includes.
727 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
728 if (*BufPtr == '#') {
729 if (++BufPtr == MainBufEnd)
730 return;
731 while (*BufPtr == ' ' || *BufPtr == '\t')
732 if (++BufPtr == MainBufEnd)
733 return;
734 if (!strncmp(BufPtr, "import", ImportLen)) {
735 // replace import with include
736 SourceLocation ImportLoc =
737 LocStart.getLocWithOffset(BufPtr-MainBufStart);
738 ReplaceText(ImportLoc, ImportLen, "include");
739 BufPtr += ImportLen;
740 }
741 }
742 }
743}
744
745static std::string getIvarAccessString(ObjCIvarDecl *OID) {
746 const ObjCInterfaceDecl *ClassDecl = OID->getContainingInterface();
747 std::string S;
748 S = "((struct ";
749 S += ClassDecl->getIdentifier()->getName();
750 S += "_IMPL *)self)->";
751 S += OID->getName();
752 return S;
753}
754
755void RewriteModernObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
756 ObjCImplementationDecl *IMD,
757 ObjCCategoryImplDecl *CID) {
758 static bool objcGetPropertyDefined = false;
759 static bool objcSetPropertyDefined = false;
760 SourceLocation startLoc = PID->getLocStart();
761 InsertText(startLoc, "// ");
762 const char *startBuf = SM->getCharacterData(startLoc);
763 assert((*startBuf == '@') && "bogus @synthesize location");
764 const char *semiBuf = strchr(startBuf, ';');
765 assert((*semiBuf == ';') && "@synthesize: can't find ';'");
766 SourceLocation onePastSemiLoc =
767 startLoc.getLocWithOffset(semiBuf-startBuf+1);
768
769 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
770 return; // FIXME: is this correct?
771
772 // Generate the 'getter' function.
773 ObjCPropertyDecl *PD = PID->getPropertyDecl();
774 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
775
776 if (!OID)
777 return;
778 unsigned Attributes = PD->getPropertyAttributes();
779 if (!PD->getGetterMethodDecl()->isDefined()) {
780 bool GenGetProperty = !(Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic) &&
781 (Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
782 ObjCPropertyDecl::OBJC_PR_copy));
783 std::string Getr;
784 if (GenGetProperty && !objcGetPropertyDefined) {
785 objcGetPropertyDefined = true;
786 // FIXME. Is this attribute correct in all cases?
787 Getr = "\nextern \"C\" __declspec(dllimport) "
788 "id objc_getProperty(id, SEL, long, bool);\n";
789 }
790 RewriteObjCMethodDecl(OID->getContainingInterface(),
791 PD->getGetterMethodDecl(), Getr);
792 Getr += "{ ";
793 // Synthesize an explicit cast to gain access to the ivar.
794 // See objc-act.c:objc_synthesize_new_getter() for details.
795 if (GenGetProperty) {
796 // return objc_getProperty(self, _cmd, offsetof(ClassDecl, OID), 1)
797 Getr += "typedef ";
798 const FunctionType *FPRetType = 0;
799 RewriteTypeIntoString(PD->getGetterMethodDecl()->getResultType(), Getr,
800 FPRetType);
801 Getr += " _TYPE";
802 if (FPRetType) {
803 Getr += ")"; // close the precedence "scope" for "*".
804
805 // Now, emit the argument types (if any).
806 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)){
807 Getr += "(";
808 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
809 if (i) Getr += ", ";
810 std::string ParamStr = FT->getArgType(i).getAsString(
811 Context->getPrintingPolicy());
812 Getr += ParamStr;
813 }
814 if (FT->isVariadic()) {
815 if (FT->getNumArgs()) Getr += ", ";
816 Getr += "...";
817 }
818 Getr += ")";
819 } else
820 Getr += "()";
821 }
822 Getr += ";\n";
823 Getr += "return (_TYPE)";
824 Getr += "objc_getProperty(self, _cmd, ";
825 RewriteIvarOffsetComputation(OID, Getr);
826 Getr += ", 1)";
827 }
828 else
829 Getr += "return " + getIvarAccessString(OID);
830 Getr += "; }";
831 InsertText(onePastSemiLoc, Getr);
832 }
833
834 if (PD->isReadOnly() || PD->getSetterMethodDecl()->isDefined())
835 return;
836
837 // Generate the 'setter' function.
838 std::string Setr;
839 bool GenSetProperty = Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
840 ObjCPropertyDecl::OBJC_PR_copy);
841 if (GenSetProperty && !objcSetPropertyDefined) {
842 objcSetPropertyDefined = true;
843 // FIXME. Is this attribute correct in all cases?
844 Setr = "\nextern \"C\" __declspec(dllimport) "
845 "void objc_setProperty (id, SEL, long, id, bool, bool);\n";
846 }
847
848 RewriteObjCMethodDecl(OID->getContainingInterface(),
849 PD->getSetterMethodDecl(), Setr);
850 Setr += "{ ";
851 // Synthesize an explicit cast to initialize the ivar.
852 // See objc-act.c:objc_synthesize_new_setter() for details.
853 if (GenSetProperty) {
854 Setr += "objc_setProperty (self, _cmd, ";
855 RewriteIvarOffsetComputation(OID, Setr);
856 Setr += ", (id)";
857 Setr += PD->getName();
858 Setr += ", ";
859 if (Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic)
860 Setr += "0, ";
861 else
862 Setr += "1, ";
863 if (Attributes & ObjCPropertyDecl::OBJC_PR_copy)
864 Setr += "1)";
865 else
866 Setr += "0)";
867 }
868 else {
869 Setr += getIvarAccessString(OID) + " = ";
870 Setr += PD->getName();
871 }
872 Setr += "; }";
873 InsertText(onePastSemiLoc, Setr);
874}
875
876static void RewriteOneForwardClassDecl(ObjCInterfaceDecl *ForwardDecl,
877 std::string &typedefString) {
878 typedefString += "#ifndef _REWRITER_typedef_";
879 typedefString += ForwardDecl->getNameAsString();
880 typedefString += "\n";
881 typedefString += "#define _REWRITER_typedef_";
882 typedefString += ForwardDecl->getNameAsString();
883 typedefString += "\n";
884 typedefString += "typedef struct objc_object ";
885 typedefString += ForwardDecl->getNameAsString();
Fariborz Jahanianc38503b2012-03-12 23:58:28 +0000886 // typedef struct { } _objc_exc_Classname;
887 typedefString += ";\ntypedef struct {} _objc_exc_";
888 typedefString += ForwardDecl->getNameAsString();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000889 typedefString += ";\n#endif\n";
890}
891
892void RewriteModernObjC::RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
893 const std::string &typedefString) {
894 SourceLocation startLoc = ClassDecl->getLocStart();
895 const char *startBuf = SM->getCharacterData(startLoc);
896 const char *semiPtr = strchr(startBuf, ';');
897 // Replace the @class with typedefs corresponding to the classes.
898 ReplaceText(startLoc, semiPtr-startBuf+1, typedefString);
899}
900
901void RewriteModernObjC::RewriteForwardClassDecl(DeclGroupRef D) {
902 std::string typedefString;
903 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
904 ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(*I);
905 if (I == D.begin()) {
906 // Translate to typedef's that forward reference structs with the same name
907 // as the class. As a convenience, we include the original declaration
908 // as a comment.
909 typedefString += "// @class ";
910 typedefString += ForwardDecl->getNameAsString();
911 typedefString += ";\n";
912 }
913 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
914 }
915 DeclGroupRef::iterator I = D.begin();
916 RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(*I), typedefString);
917}
918
919void RewriteModernObjC::RewriteForwardClassDecl(
920 const llvm::SmallVector<Decl*, 8> &D) {
921 std::string typedefString;
922 for (unsigned i = 0; i < D.size(); i++) {
923 ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(D[i]);
924 if (i == 0) {
925 typedefString += "// @class ";
926 typedefString += ForwardDecl->getNameAsString();
927 typedefString += ";\n";
928 }
929 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
930 }
931 RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(D[0]), typedefString);
932}
933
934void RewriteModernObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
935 // When method is a synthesized one, such as a getter/setter there is
936 // nothing to rewrite.
937 if (Method->isImplicit())
938 return;
939 SourceLocation LocStart = Method->getLocStart();
940 SourceLocation LocEnd = Method->getLocEnd();
941
942 if (SM->getExpansionLineNumber(LocEnd) >
943 SM->getExpansionLineNumber(LocStart)) {
944 InsertText(LocStart, "#if 0\n");
945 ReplaceText(LocEnd, 1, ";\n#endif\n");
946 } else {
947 InsertText(LocStart, "// ");
948 }
949}
950
951void RewriteModernObjC::RewriteProperty(ObjCPropertyDecl *prop) {
952 SourceLocation Loc = prop->getAtLoc();
953
954 ReplaceText(Loc, 0, "// ");
955 // FIXME: handle properties that are declared across multiple lines.
956}
957
958void RewriteModernObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
959 SourceLocation LocStart = CatDecl->getLocStart();
960
961 // FIXME: handle category headers that are declared across multiple lines.
962 ReplaceText(LocStart, 0, "// ");
Fariborz Jahanianaf300292012-02-20 20:09:20 +0000963 if (CatDecl->getIvarLBraceLoc().isValid())
964 InsertText(CatDecl->getIvarLBraceLoc(), "// ");
Fariborz Jahaniand2aea122012-02-19 19:00:05 +0000965 for (ObjCCategoryDecl::ivar_iterator
966 I = CatDecl->ivar_begin(), E = CatDecl->ivar_end(); I != E; ++I) {
967 ObjCIvarDecl *Ivar = (*I);
968 SourceLocation LocStart = Ivar->getLocStart();
969 ReplaceText(LocStart, 0, "// ");
970 }
Fariborz Jahanianaf300292012-02-20 20:09:20 +0000971 if (CatDecl->getIvarRBraceLoc().isValid())
972 InsertText(CatDecl->getIvarRBraceLoc(), "// ");
973
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000974 for (ObjCCategoryDecl::prop_iterator I = CatDecl->prop_begin(),
975 E = CatDecl->prop_end(); I != E; ++I)
976 RewriteProperty(*I);
977
978 for (ObjCCategoryDecl::instmeth_iterator
979 I = CatDecl->instmeth_begin(), E = CatDecl->instmeth_end();
980 I != E; ++I)
981 RewriteMethodDeclaration(*I);
982 for (ObjCCategoryDecl::classmeth_iterator
983 I = CatDecl->classmeth_begin(), E = CatDecl->classmeth_end();
984 I != E; ++I)
985 RewriteMethodDeclaration(*I);
986
987 // Lastly, comment out the @end.
988 ReplaceText(CatDecl->getAtEndRange().getBegin(),
989 strlen("@end"), "/* @end */");
990}
991
992void RewriteModernObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
993 SourceLocation LocStart = PDecl->getLocStart();
994 assert(PDecl->isThisDeclarationADefinition());
995
996 // FIXME: handle protocol headers that are declared across multiple lines.
997 ReplaceText(LocStart, 0, "// ");
998
999 for (ObjCProtocolDecl::instmeth_iterator
1000 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
1001 I != E; ++I)
1002 RewriteMethodDeclaration(*I);
1003 for (ObjCProtocolDecl::classmeth_iterator
1004 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
1005 I != E; ++I)
1006 RewriteMethodDeclaration(*I);
1007
1008 for (ObjCInterfaceDecl::prop_iterator I = PDecl->prop_begin(),
1009 E = PDecl->prop_end(); I != E; ++I)
1010 RewriteProperty(*I);
1011
1012 // Lastly, comment out the @end.
1013 SourceLocation LocEnd = PDecl->getAtEndRange().getBegin();
1014 ReplaceText(LocEnd, strlen("@end"), "/* @end */");
1015
1016 // Must comment out @optional/@required
1017 const char *startBuf = SM->getCharacterData(LocStart);
1018 const char *endBuf = SM->getCharacterData(LocEnd);
1019 for (const char *p = startBuf; p < endBuf; p++) {
1020 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
1021 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
1022 ReplaceText(OptionalLoc, strlen("@optional"), "/* @optional */");
1023
1024 }
1025 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
1026 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
1027 ReplaceText(OptionalLoc, strlen("@required"), "/* @required */");
1028
1029 }
1030 }
1031}
1032
1033void RewriteModernObjC::RewriteForwardProtocolDecl(DeclGroupRef D) {
1034 SourceLocation LocStart = (*D.begin())->getLocStart();
1035 if (LocStart.isInvalid())
1036 llvm_unreachable("Invalid SourceLocation");
1037 // FIXME: handle forward protocol that are declared across multiple lines.
1038 ReplaceText(LocStart, 0, "// ");
1039}
1040
1041void
1042RewriteModernObjC::RewriteForwardProtocolDecl(const llvm::SmallVector<Decl*, 8> &DG) {
1043 SourceLocation LocStart = DG[0]->getLocStart();
1044 if (LocStart.isInvalid())
1045 llvm_unreachable("Invalid SourceLocation");
1046 // FIXME: handle forward protocol that are declared across multiple lines.
1047 ReplaceText(LocStart, 0, "// ");
1048}
1049
1050void RewriteModernObjC::RewriteTypeIntoString(QualType T, std::string &ResultStr,
1051 const FunctionType *&FPRetType) {
1052 if (T->isObjCQualifiedIdType())
1053 ResultStr += "id";
1054 else if (T->isFunctionPointerType() ||
1055 T->isBlockPointerType()) {
1056 // needs special handling, since pointer-to-functions have special
1057 // syntax (where a decaration models use).
1058 QualType retType = T;
1059 QualType PointeeTy;
1060 if (const PointerType* PT = retType->getAs<PointerType>())
1061 PointeeTy = PT->getPointeeType();
1062 else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
1063 PointeeTy = BPT->getPointeeType();
1064 if ((FPRetType = PointeeTy->getAs<FunctionType>())) {
1065 ResultStr += FPRetType->getResultType().getAsString(
1066 Context->getPrintingPolicy());
1067 ResultStr += "(*";
1068 }
1069 } else
1070 ResultStr += T.getAsString(Context->getPrintingPolicy());
1071}
1072
1073void RewriteModernObjC::RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
1074 ObjCMethodDecl *OMD,
1075 std::string &ResultStr) {
1076 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
1077 const FunctionType *FPRetType = 0;
1078 ResultStr += "\nstatic ";
1079 RewriteTypeIntoString(OMD->getResultType(), ResultStr, FPRetType);
1080 ResultStr += " ";
1081
1082 // Unique method name
1083 std::string NameStr;
1084
1085 if (OMD->isInstanceMethod())
1086 NameStr += "_I_";
1087 else
1088 NameStr += "_C_";
1089
1090 NameStr += IDecl->getNameAsString();
1091 NameStr += "_";
1092
1093 if (ObjCCategoryImplDecl *CID =
1094 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
1095 NameStr += CID->getNameAsString();
1096 NameStr += "_";
1097 }
1098 // Append selector names, replacing ':' with '_'
1099 {
1100 std::string selString = OMD->getSelector().getAsString();
1101 int len = selString.size();
1102 for (int i = 0; i < len; i++)
1103 if (selString[i] == ':')
1104 selString[i] = '_';
1105 NameStr += selString;
1106 }
1107 // Remember this name for metadata emission
1108 MethodInternalNames[OMD] = NameStr;
1109 ResultStr += NameStr;
1110
1111 // Rewrite arguments
1112 ResultStr += "(";
1113
1114 // invisible arguments
1115 if (OMD->isInstanceMethod()) {
1116 QualType selfTy = Context->getObjCInterfaceType(IDecl);
1117 selfTy = Context->getPointerType(selfTy);
1118 if (!LangOpts.MicrosoftExt) {
1119 if (ObjCSynthesizedStructs.count(const_cast<ObjCInterfaceDecl*>(IDecl)))
1120 ResultStr += "struct ";
1121 }
1122 // When rewriting for Microsoft, explicitly omit the structure name.
1123 ResultStr += IDecl->getNameAsString();
1124 ResultStr += " *";
1125 }
1126 else
1127 ResultStr += Context->getObjCClassType().getAsString(
1128 Context->getPrintingPolicy());
1129
1130 ResultStr += " self, ";
1131 ResultStr += Context->getObjCSelType().getAsString(Context->getPrintingPolicy());
1132 ResultStr += " _cmd";
1133
1134 // Method arguments.
1135 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
1136 E = OMD->param_end(); PI != E; ++PI) {
1137 ParmVarDecl *PDecl = *PI;
1138 ResultStr += ", ";
1139 if (PDecl->getType()->isObjCQualifiedIdType()) {
1140 ResultStr += "id ";
1141 ResultStr += PDecl->getNameAsString();
1142 } else {
1143 std::string Name = PDecl->getNameAsString();
1144 QualType QT = PDecl->getType();
1145 // Make sure we convert "t (^)(...)" to "t (*)(...)".
1146 if (convertBlockPointerToFunctionPointer(QT))
1147 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
1148 else
1149 PDecl->getType().getAsStringInternal(Name, Context->getPrintingPolicy());
1150 ResultStr += Name;
1151 }
1152 }
1153 if (OMD->isVariadic())
1154 ResultStr += ", ...";
1155 ResultStr += ") ";
1156
1157 if (FPRetType) {
1158 ResultStr += ")"; // close the precedence "scope" for "*".
1159
1160 // Now, emit the argument types (if any).
1161 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
1162 ResultStr += "(";
1163 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
1164 if (i) ResultStr += ", ";
1165 std::string ParamStr = FT->getArgType(i).getAsString(
1166 Context->getPrintingPolicy());
1167 ResultStr += ParamStr;
1168 }
1169 if (FT->isVariadic()) {
1170 if (FT->getNumArgs()) ResultStr += ", ";
1171 ResultStr += "...";
1172 }
1173 ResultStr += ")";
1174 } else {
1175 ResultStr += "()";
1176 }
1177 }
1178}
1179void RewriteModernObjC::RewriteImplementationDecl(Decl *OID) {
1180 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
1181 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
1182
Fariborz Jahaniand2aea122012-02-19 19:00:05 +00001183 if (IMD) {
1184 InsertText(IMD->getLocStart(), "// ");
Fariborz Jahanianaf300292012-02-20 20:09:20 +00001185 if (IMD->getIvarLBraceLoc().isValid())
1186 InsertText(IMD->getIvarLBraceLoc(), "// ");
1187 for (ObjCImplementationDecl::ivar_iterator
1188 I = IMD->ivar_begin(), E = IMD->ivar_end(); I != E; ++I) {
1189 ObjCIvarDecl *Ivar = (*I);
1190 SourceLocation LocStart = Ivar->getLocStart();
1191 ReplaceText(LocStart, 0, "// ");
Fariborz Jahaniand2aea122012-02-19 19:00:05 +00001192 }
Fariborz Jahanianaf300292012-02-20 20:09:20 +00001193 if (IMD->getIvarRBraceLoc().isValid())
1194 InsertText(IMD->getIvarRBraceLoc(), "// ");
Fariborz Jahaniand2aea122012-02-19 19:00:05 +00001195 }
1196 else
1197 InsertText(CID->getLocStart(), "// ");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001198
1199 for (ObjCCategoryImplDecl::instmeth_iterator
1200 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
1201 E = IMD ? IMD->instmeth_end() : CID->instmeth_end();
1202 I != E; ++I) {
1203 std::string ResultStr;
1204 ObjCMethodDecl *OMD = *I;
1205 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
1206 SourceLocation LocStart = OMD->getLocStart();
1207 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
1208
1209 const char *startBuf = SM->getCharacterData(LocStart);
1210 const char *endBuf = SM->getCharacterData(LocEnd);
1211 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
1212 }
1213
1214 for (ObjCCategoryImplDecl::classmeth_iterator
1215 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
1216 E = IMD ? IMD->classmeth_end() : CID->classmeth_end();
1217 I != E; ++I) {
1218 std::string ResultStr;
1219 ObjCMethodDecl *OMD = *I;
1220 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
1221 SourceLocation LocStart = OMD->getLocStart();
1222 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
1223
1224 const char *startBuf = SM->getCharacterData(LocStart);
1225 const char *endBuf = SM->getCharacterData(LocEnd);
1226 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
1227 }
1228 for (ObjCCategoryImplDecl::propimpl_iterator
1229 I = IMD ? IMD->propimpl_begin() : CID->propimpl_begin(),
1230 E = IMD ? IMD->propimpl_end() : CID->propimpl_end();
1231 I != E; ++I) {
1232 RewritePropertyImplDecl(*I, IMD, CID);
1233 }
1234
1235 InsertText(IMD ? IMD->getLocEnd() : CID->getLocEnd(), "// ");
1236}
1237
1238void RewriteModernObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00001239 // Do not synthesize more than once.
1240 if (ObjCSynthesizedStructs.count(ClassDecl))
1241 return;
1242 // Make sure super class's are written before current class is written.
1243 ObjCInterfaceDecl *SuperClass = ClassDecl->getSuperClass();
1244 while (SuperClass) {
1245 RewriteInterfaceDecl(SuperClass);
1246 SuperClass = SuperClass->getSuperClass();
1247 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001248 std::string ResultStr;
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +00001249 if (!ObjCWrittenInterfaces.count(ClassDecl->getCanonicalDecl())) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001250 // we haven't seen a forward decl - generate a typedef.
Fariborz Jahanianc38503b2012-03-12 23:58:28 +00001251 RewriteOneForwardClassDecl(ClassDecl, ResultStr);
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00001252 RewriteIvarOffsetSymbols(ClassDecl, ResultStr);
1253
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001254 RewriteObjCInternalStruct(ClassDecl, ResultStr);
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +00001255 // Mark this typedef as having been written into its c++ equivalent.
1256 ObjCWrittenInterfaces.insert(ClassDecl->getCanonicalDecl());
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001257
1258 for (ObjCInterfaceDecl::prop_iterator I = ClassDecl->prop_begin(),
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001259 E = ClassDecl->prop_end(); I != E; ++I)
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001260 RewriteProperty(*I);
1261 for (ObjCInterfaceDecl::instmeth_iterator
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001262 I = ClassDecl->instmeth_begin(), E = ClassDecl->instmeth_end();
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001263 I != E; ++I)
1264 RewriteMethodDeclaration(*I);
1265 for (ObjCInterfaceDecl::classmeth_iterator
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001266 I = ClassDecl->classmeth_begin(), E = ClassDecl->classmeth_end();
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001267 I != E; ++I)
1268 RewriteMethodDeclaration(*I);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001269
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001270 // Lastly, comment out the @end.
1271 ReplaceText(ClassDecl->getAtEndRange().getBegin(), strlen("@end"),
1272 "/* @end */");
1273 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001274}
1275
1276Stmt *RewriteModernObjC::RewritePropertyOrImplicitSetter(PseudoObjectExpr *PseudoOp) {
1277 SourceRange OldRange = PseudoOp->getSourceRange();
1278
1279 // We just magically know some things about the structure of this
1280 // expression.
1281 ObjCMessageExpr *OldMsg =
1282 cast<ObjCMessageExpr>(PseudoOp->getSemanticExpr(
1283 PseudoOp->getNumSemanticExprs() - 1));
1284
1285 // Because the rewriter doesn't allow us to rewrite rewritten code,
1286 // we need to suppress rewriting the sub-statements.
1287 Expr *Base, *RHS;
1288 {
1289 DisableReplaceStmtScope S(*this);
1290
1291 // Rebuild the base expression if we have one.
1292 Base = 0;
1293 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1294 Base = OldMsg->getInstanceReceiver();
1295 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1296 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1297 }
1298
1299 // Rebuild the RHS.
1300 RHS = cast<BinaryOperator>(PseudoOp->getSyntacticForm())->getRHS();
1301 RHS = cast<OpaqueValueExpr>(RHS)->getSourceExpr();
1302 RHS = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(RHS));
1303 }
1304
1305 // TODO: avoid this copy.
1306 SmallVector<SourceLocation, 1> SelLocs;
1307 OldMsg->getSelectorLocs(SelLocs);
1308
1309 ObjCMessageExpr *NewMsg = 0;
1310 switch (OldMsg->getReceiverKind()) {
1311 case ObjCMessageExpr::Class:
1312 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1313 OldMsg->getValueKind(),
1314 OldMsg->getLeftLoc(),
1315 OldMsg->getClassReceiverTypeInfo(),
1316 OldMsg->getSelector(),
1317 SelLocs,
1318 OldMsg->getMethodDecl(),
1319 RHS,
1320 OldMsg->getRightLoc(),
1321 OldMsg->isImplicit());
1322 break;
1323
1324 case ObjCMessageExpr::Instance:
1325 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1326 OldMsg->getValueKind(),
1327 OldMsg->getLeftLoc(),
1328 Base,
1329 OldMsg->getSelector(),
1330 SelLocs,
1331 OldMsg->getMethodDecl(),
1332 RHS,
1333 OldMsg->getRightLoc(),
1334 OldMsg->isImplicit());
1335 break;
1336
1337 case ObjCMessageExpr::SuperClass:
1338 case ObjCMessageExpr::SuperInstance:
1339 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1340 OldMsg->getValueKind(),
1341 OldMsg->getLeftLoc(),
1342 OldMsg->getSuperLoc(),
1343 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1344 OldMsg->getSuperType(),
1345 OldMsg->getSelector(),
1346 SelLocs,
1347 OldMsg->getMethodDecl(),
1348 RHS,
1349 OldMsg->getRightLoc(),
1350 OldMsg->isImplicit());
1351 break;
1352 }
1353
1354 Stmt *Replacement = SynthMessageExpr(NewMsg);
1355 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1356 return Replacement;
1357}
1358
1359Stmt *RewriteModernObjC::RewritePropertyOrImplicitGetter(PseudoObjectExpr *PseudoOp) {
1360 SourceRange OldRange = PseudoOp->getSourceRange();
1361
1362 // We just magically know some things about the structure of this
1363 // expression.
1364 ObjCMessageExpr *OldMsg =
1365 cast<ObjCMessageExpr>(PseudoOp->getResultExpr()->IgnoreImplicit());
1366
1367 // Because the rewriter doesn't allow us to rewrite rewritten code,
1368 // we need to suppress rewriting the sub-statements.
1369 Expr *Base = 0;
1370 {
1371 DisableReplaceStmtScope S(*this);
1372
1373 // Rebuild the base expression if we have one.
1374 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1375 Base = OldMsg->getInstanceReceiver();
1376 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1377 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1378 }
1379 }
1380
1381 // Intentionally empty.
1382 SmallVector<SourceLocation, 1> SelLocs;
1383 SmallVector<Expr*, 1> Args;
1384
1385 ObjCMessageExpr *NewMsg = 0;
1386 switch (OldMsg->getReceiverKind()) {
1387 case ObjCMessageExpr::Class:
1388 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1389 OldMsg->getValueKind(),
1390 OldMsg->getLeftLoc(),
1391 OldMsg->getClassReceiverTypeInfo(),
1392 OldMsg->getSelector(),
1393 SelLocs,
1394 OldMsg->getMethodDecl(),
1395 Args,
1396 OldMsg->getRightLoc(),
1397 OldMsg->isImplicit());
1398 break;
1399
1400 case ObjCMessageExpr::Instance:
1401 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1402 OldMsg->getValueKind(),
1403 OldMsg->getLeftLoc(),
1404 Base,
1405 OldMsg->getSelector(),
1406 SelLocs,
1407 OldMsg->getMethodDecl(),
1408 Args,
1409 OldMsg->getRightLoc(),
1410 OldMsg->isImplicit());
1411 break;
1412
1413 case ObjCMessageExpr::SuperClass:
1414 case ObjCMessageExpr::SuperInstance:
1415 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1416 OldMsg->getValueKind(),
1417 OldMsg->getLeftLoc(),
1418 OldMsg->getSuperLoc(),
1419 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1420 OldMsg->getSuperType(),
1421 OldMsg->getSelector(),
1422 SelLocs,
1423 OldMsg->getMethodDecl(),
1424 Args,
1425 OldMsg->getRightLoc(),
1426 OldMsg->isImplicit());
1427 break;
1428 }
1429
1430 Stmt *Replacement = SynthMessageExpr(NewMsg);
1431 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1432 return Replacement;
1433}
1434
1435/// SynthCountByEnumWithState - To print:
1436/// ((unsigned int (*)
1437/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1438/// (void *)objc_msgSend)((id)l_collection,
1439/// sel_registerName(
1440/// "countByEnumeratingWithState:objects:count:"),
1441/// &enumState,
1442/// (id *)__rw_items, (unsigned int)16)
1443///
1444void RewriteModernObjC::SynthCountByEnumWithState(std::string &buf) {
1445 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1446 "id *, unsigned int))(void *)objc_msgSend)";
1447 buf += "\n\t\t";
1448 buf += "((id)l_collection,\n\t\t";
1449 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1450 buf += "\n\t\t";
1451 buf += "&enumState, "
1452 "(id *)__rw_items, (unsigned int)16)";
1453}
1454
1455/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1456/// statement to exit to its outer synthesized loop.
1457///
1458Stmt *RewriteModernObjC::RewriteBreakStmt(BreakStmt *S) {
1459 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1460 return S;
1461 // replace break with goto __break_label
1462 std::string buf;
1463
1464 SourceLocation startLoc = S->getLocStart();
1465 buf = "goto __break_label_";
1466 buf += utostr(ObjCBcLabelNo.back());
1467 ReplaceText(startLoc, strlen("break"), buf);
1468
1469 return 0;
1470}
1471
1472/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1473/// statement to continue with its inner synthesized loop.
1474///
1475Stmt *RewriteModernObjC::RewriteContinueStmt(ContinueStmt *S) {
1476 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1477 return S;
1478 // replace continue with goto __continue_label
1479 std::string buf;
1480
1481 SourceLocation startLoc = S->getLocStart();
1482 buf = "goto __continue_label_";
1483 buf += utostr(ObjCBcLabelNo.back());
1484 ReplaceText(startLoc, strlen("continue"), buf);
1485
1486 return 0;
1487}
1488
1489/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
1490/// It rewrites:
1491/// for ( type elem in collection) { stmts; }
1492
1493/// Into:
1494/// {
1495/// type elem;
1496/// struct __objcFastEnumerationState enumState = { 0 };
1497/// id __rw_items[16];
1498/// id l_collection = (id)collection;
1499/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1500/// objects:__rw_items count:16];
1501/// if (limit) {
1502/// unsigned long startMutations = *enumState.mutationsPtr;
1503/// do {
1504/// unsigned long counter = 0;
1505/// do {
1506/// if (startMutations != *enumState.mutationsPtr)
1507/// objc_enumerationMutation(l_collection);
1508/// elem = (type)enumState.itemsPtr[counter++];
1509/// stmts;
1510/// __continue_label: ;
1511/// } while (counter < limit);
1512/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1513/// objects:__rw_items count:16]);
1514/// elem = nil;
1515/// __break_label: ;
1516/// }
1517/// else
1518/// elem = nil;
1519/// }
1520///
1521Stmt *RewriteModernObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
1522 SourceLocation OrigEnd) {
1523 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
1524 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
1525 "ObjCForCollectionStmt Statement stack mismatch");
1526 assert(!ObjCBcLabelNo.empty() &&
1527 "ObjCForCollectionStmt - Label No stack empty");
1528
1529 SourceLocation startLoc = S->getLocStart();
1530 const char *startBuf = SM->getCharacterData(startLoc);
1531 StringRef elementName;
1532 std::string elementTypeAsString;
1533 std::string buf;
1534 buf = "\n{\n\t";
1535 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1536 // type elem;
1537 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
1538 QualType ElementType = cast<ValueDecl>(D)->getType();
1539 if (ElementType->isObjCQualifiedIdType() ||
1540 ElementType->isObjCQualifiedInterfaceType())
1541 // Simply use 'id' for all qualified types.
1542 elementTypeAsString = "id";
1543 else
1544 elementTypeAsString = ElementType.getAsString(Context->getPrintingPolicy());
1545 buf += elementTypeAsString;
1546 buf += " ";
1547 elementName = D->getName();
1548 buf += elementName;
1549 buf += ";\n\t";
1550 }
1551 else {
1552 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
1553 elementName = DR->getDecl()->getName();
1554 ValueDecl *VD = cast<ValueDecl>(DR->getDecl());
1555 if (VD->getType()->isObjCQualifiedIdType() ||
1556 VD->getType()->isObjCQualifiedInterfaceType())
1557 // Simply use 'id' for all qualified types.
1558 elementTypeAsString = "id";
1559 else
1560 elementTypeAsString = VD->getType().getAsString(Context->getPrintingPolicy());
1561 }
1562
1563 // struct __objcFastEnumerationState enumState = { 0 };
1564 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1565 // id __rw_items[16];
1566 buf += "id __rw_items[16];\n\t";
1567 // id l_collection = (id)
1568 buf += "id l_collection = (id)";
1569 // Find start location of 'collection' the hard way!
1570 const char *startCollectionBuf = startBuf;
1571 startCollectionBuf += 3; // skip 'for'
1572 startCollectionBuf = strchr(startCollectionBuf, '(');
1573 startCollectionBuf++; // skip '('
1574 // find 'in' and skip it.
1575 while (*startCollectionBuf != ' ' ||
1576 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1577 (*(startCollectionBuf+3) != ' ' &&
1578 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1579 startCollectionBuf++;
1580 startCollectionBuf += 3;
1581
1582 // Replace: "for (type element in" with string constructed thus far.
1583 ReplaceText(startLoc, startCollectionBuf - startBuf, buf);
1584 // Replace ')' in for '(' type elem in collection ')' with ';'
1585 SourceLocation rightParenLoc = S->getRParenLoc();
1586 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1587 SourceLocation lparenLoc = startLoc.getLocWithOffset(rparenBuf-startBuf);
1588 buf = ";\n\t";
1589
1590 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1591 // objects:__rw_items count:16];
1592 // which is synthesized into:
1593 // unsigned int limit =
1594 // ((unsigned int (*)
1595 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1596 // (void *)objc_msgSend)((id)l_collection,
1597 // sel_registerName(
1598 // "countByEnumeratingWithState:objects:count:"),
1599 // (struct __objcFastEnumerationState *)&state,
1600 // (id *)__rw_items, (unsigned int)16);
1601 buf += "unsigned long limit =\n\t\t";
1602 SynthCountByEnumWithState(buf);
1603 buf += ";\n\t";
1604 /// if (limit) {
1605 /// unsigned long startMutations = *enumState.mutationsPtr;
1606 /// do {
1607 /// unsigned long counter = 0;
1608 /// do {
1609 /// if (startMutations != *enumState.mutationsPtr)
1610 /// objc_enumerationMutation(l_collection);
1611 /// elem = (type)enumState.itemsPtr[counter++];
1612 buf += "if (limit) {\n\t";
1613 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1614 buf += "do {\n\t\t";
1615 buf += "unsigned long counter = 0;\n\t\t";
1616 buf += "do {\n\t\t\t";
1617 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1618 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1619 buf += elementName;
1620 buf += " = (";
1621 buf += elementTypeAsString;
1622 buf += ")enumState.itemsPtr[counter++];";
1623 // Replace ')' in for '(' type elem in collection ')' with all of these.
1624 ReplaceText(lparenLoc, 1, buf);
1625
1626 /// __continue_label: ;
1627 /// } while (counter < limit);
1628 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1629 /// objects:__rw_items count:16]);
1630 /// elem = nil;
1631 /// __break_label: ;
1632 /// }
1633 /// else
1634 /// elem = nil;
1635 /// }
1636 ///
1637 buf = ";\n\t";
1638 buf += "__continue_label_";
1639 buf += utostr(ObjCBcLabelNo.back());
1640 buf += ": ;";
1641 buf += "\n\t\t";
1642 buf += "} while (counter < limit);\n\t";
1643 buf += "} while (limit = ";
1644 SynthCountByEnumWithState(buf);
1645 buf += ");\n\t";
1646 buf += elementName;
1647 buf += " = ((";
1648 buf += elementTypeAsString;
1649 buf += ")0);\n\t";
1650 buf += "__break_label_";
1651 buf += utostr(ObjCBcLabelNo.back());
1652 buf += ": ;\n\t";
1653 buf += "}\n\t";
1654 buf += "else\n\t\t";
1655 buf += elementName;
1656 buf += " = ((";
1657 buf += elementTypeAsString;
1658 buf += ")0);\n\t";
1659 buf += "}\n";
1660
1661 // Insert all these *after* the statement body.
1662 // FIXME: If this should support Obj-C++, support CXXTryStmt
1663 if (isa<CompoundStmt>(S->getBody())) {
1664 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(1);
1665 InsertText(endBodyLoc, buf);
1666 } else {
1667 /* Need to treat single statements specially. For example:
1668 *
1669 * for (A *a in b) if (stuff()) break;
1670 * for (A *a in b) xxxyy;
1671 *
1672 * The following code simply scans ahead to the semi to find the actual end.
1673 */
1674 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1675 const char *semiBuf = strchr(stmtBuf, ';');
1676 assert(semiBuf && "Can't find ';'");
1677 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(semiBuf-stmtBuf+1);
1678 InsertText(endBodyLoc, buf);
1679 }
1680 Stmts.pop_back();
1681 ObjCBcLabelNo.pop_back();
1682 return 0;
1683}
1684
1685/// RewriteObjCSynchronizedStmt -
1686/// This routine rewrites @synchronized(expr) stmt;
1687/// into:
1688/// objc_sync_enter(expr);
1689/// @try stmt @finally { objc_sync_exit(expr); }
1690///
1691Stmt *RewriteModernObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
1692 // Get the start location and compute the semi location.
1693 SourceLocation startLoc = S->getLocStart();
1694 const char *startBuf = SM->getCharacterData(startLoc);
1695
1696 assert((*startBuf == '@') && "bogus @synchronized location");
1697
1698 std::string buf;
1699 buf = "objc_sync_enter((id)";
1700 const char *lparenBuf = startBuf;
1701 while (*lparenBuf != '(') lparenBuf++;
1702 ReplaceText(startLoc, lparenBuf-startBuf+1, buf);
1703 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1704 // the sync expression is typically a message expression that's already
1705 // been rewritten! (which implies the SourceLocation's are invalid).
1706 SourceLocation endLoc = S->getSynchBody()->getLocStart();
1707 const char *endBuf = SM->getCharacterData(endLoc);
1708 while (*endBuf != ')') endBuf--;
1709 SourceLocation rparenLoc = startLoc.getLocWithOffset(endBuf-startBuf);
1710 buf = ");\n";
1711 // declare a new scope with two variables, _stack and _rethrow.
1712 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1713 buf += "int buf[18/*32-bit i386*/];\n";
1714 buf += "char *pointers[4];} _stack;\n";
1715 buf += "id volatile _rethrow = 0;\n";
1716 buf += "objc_exception_try_enter(&_stack);\n";
1717 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
1718 ReplaceText(rparenLoc, 1, buf);
1719 startLoc = S->getSynchBody()->getLocEnd();
1720 startBuf = SM->getCharacterData(startLoc);
1721
1722 assert((*startBuf == '}') && "bogus @synchronized block");
1723 SourceLocation lastCurlyLoc = startLoc;
1724 buf = "}\nelse {\n";
1725 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1726 buf += "}\n";
1727 buf += "{ /* implicit finally clause */\n";
1728 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
1729
1730 std::string syncBuf;
1731 syncBuf += " objc_sync_exit(";
1732
1733 Expr *syncExpr = S->getSynchExpr();
1734 CastKind CK = syncExpr->getType()->isObjCObjectPointerType()
1735 ? CK_BitCast :
1736 syncExpr->getType()->isBlockPointerType()
1737 ? CK_BlockPointerToObjCPointerCast
1738 : CK_CPointerToObjCPointerCast;
1739 syncExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
1740 CK, syncExpr);
1741 std::string syncExprBufS;
1742 llvm::raw_string_ostream syncExprBuf(syncExprBufS);
1743 syncExpr->printPretty(syncExprBuf, *Context, 0,
1744 PrintingPolicy(LangOpts));
1745 syncBuf += syncExprBuf.str();
1746 syncBuf += ");";
1747
1748 buf += syncBuf;
1749 buf += "\n if (_rethrow) objc_exception_throw(_rethrow);\n";
1750 buf += "}\n";
1751 buf += "}";
1752
1753 ReplaceText(lastCurlyLoc, 1, buf);
1754
1755 bool hasReturns = false;
1756 HasReturnStmts(S->getSynchBody(), hasReturns);
1757 if (hasReturns)
1758 RewriteSyncReturnStmts(S->getSynchBody(), syncBuf);
1759
1760 return 0;
1761}
1762
1763void RewriteModernObjC::WarnAboutReturnGotoStmts(Stmt *S)
1764{
1765 // Perform a bottom up traversal of all children.
1766 for (Stmt::child_range CI = S->children(); CI; ++CI)
1767 if (*CI)
1768 WarnAboutReturnGotoStmts(*CI);
1769
1770 if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
1771 Diags.Report(Context->getFullLoc(S->getLocStart()),
1772 TryFinallyContainsReturnDiag);
1773 }
1774 return;
1775}
1776
1777void RewriteModernObjC::HasReturnStmts(Stmt *S, bool &hasReturns)
1778{
1779 // Perform a bottom up traversal of all children.
1780 for (Stmt::child_range CI = S->children(); CI; ++CI)
1781 if (*CI)
1782 HasReturnStmts(*CI, hasReturns);
1783
1784 if (isa<ReturnStmt>(S))
1785 hasReturns = true;
1786 return;
1787}
1788
1789void RewriteModernObjC::RewriteTryReturnStmts(Stmt *S) {
1790 // Perform a bottom up traversal of all children.
1791 for (Stmt::child_range CI = S->children(); CI; ++CI)
1792 if (*CI) {
1793 RewriteTryReturnStmts(*CI);
1794 }
1795 if (isa<ReturnStmt>(S)) {
1796 SourceLocation startLoc = S->getLocStart();
1797 const char *startBuf = SM->getCharacterData(startLoc);
1798
1799 const char *semiBuf = strchr(startBuf, ';');
1800 assert((*semiBuf == ';') && "RewriteTryReturnStmts: can't find ';'");
1801 SourceLocation onePastSemiLoc = startLoc.getLocWithOffset(semiBuf-startBuf+1);
1802
1803 std::string buf;
1804 buf = "{ objc_exception_try_exit(&_stack); return";
1805
1806 ReplaceText(startLoc, 6, buf);
1807 InsertText(onePastSemiLoc, "}");
1808 }
1809 return;
1810}
1811
1812void RewriteModernObjC::RewriteSyncReturnStmts(Stmt *S, std::string syncExitBuf) {
1813 // Perform a bottom up traversal of all children.
1814 for (Stmt::child_range CI = S->children(); CI; ++CI)
1815 if (*CI) {
1816 RewriteSyncReturnStmts(*CI, syncExitBuf);
1817 }
1818 if (isa<ReturnStmt>(S)) {
1819 SourceLocation startLoc = S->getLocStart();
1820 const char *startBuf = SM->getCharacterData(startLoc);
1821
1822 const char *semiBuf = strchr(startBuf, ';');
1823 assert((*semiBuf == ';') && "RewriteSyncReturnStmts: can't find ';'");
1824 SourceLocation onePastSemiLoc = startLoc.getLocWithOffset(semiBuf-startBuf+1);
1825
1826 std::string buf;
1827 buf = "{ objc_exception_try_exit(&_stack);";
1828 buf += syncExitBuf;
1829 buf += " return";
1830
1831 ReplaceText(startLoc, 6, buf);
1832 InsertText(onePastSemiLoc, "}");
1833 }
1834 return;
1835}
1836
1837Stmt *RewriteModernObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
1838 // Get the start location and compute the semi location.
1839 SourceLocation startLoc = S->getLocStart();
1840 const char *startBuf = SM->getCharacterData(startLoc);
1841
1842 assert((*startBuf == '@') && "bogus @try location");
Fariborz Jahanianc38503b2012-03-12 23:58:28 +00001843 // @try -> try
1844 ReplaceText(startLoc, 1, "");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001845
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001846 for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
1847 ObjCAtCatchStmt *Catch = S->getCatchStmt(I);
Fariborz Jahanianc38503b2012-03-12 23:58:28 +00001848
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001849 startLoc = Catch->getLocStart();
1850 startBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001851 assert((*startBuf == '@') && "bogus @catch location");
Fariborz Jahanianc38503b2012-03-12 23:58:28 +00001852 // @catch -> catch
1853 ReplaceText(startLoc, 1, "");
1854
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001855 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001856 return 0;
1857}
1858
1859// This can't be done with ReplaceStmt(S, ThrowExpr), since
1860// the throw expression is typically a message expression that's already
1861// been rewritten! (which implies the SourceLocation's are invalid).
1862Stmt *RewriteModernObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
1863 // Get the start location and compute the semi location.
1864 SourceLocation startLoc = S->getLocStart();
1865 const char *startBuf = SM->getCharacterData(startLoc);
1866
1867 assert((*startBuf == '@') && "bogus @throw location");
1868
1869 std::string buf;
1870 /* void objc_exception_throw(id) __attribute__((noreturn)); */
1871 if (S->getThrowExpr())
1872 buf = "objc_exception_throw(";
1873 else // add an implicit argument
1874 buf = "objc_exception_throw(_caught";
1875
1876 // handle "@ throw" correctly.
1877 const char *wBuf = strchr(startBuf, 'w');
1878 assert((*wBuf == 'w') && "@throw: can't find 'w'");
1879 ReplaceText(startLoc, wBuf-startBuf+1, buf);
1880
1881 const char *semiBuf = strchr(startBuf, ';');
1882 assert((*semiBuf == ';') && "@throw: can't find ';'");
1883 SourceLocation semiLoc = startLoc.getLocWithOffset(semiBuf-startBuf);
1884 ReplaceText(semiLoc, 1, ");");
1885 return 0;
1886}
1887
1888Stmt *RewriteModernObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
1889 // Create a new string expression.
1890 QualType StrType = Context->getPointerType(Context->CharTy);
1891 std::string StrEncoding;
1892 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
1893 Expr *Replacement = StringLiteral::Create(*Context, StrEncoding,
1894 StringLiteral::Ascii, false,
1895 StrType, SourceLocation());
1896 ReplaceStmt(Exp, Replacement);
1897
1898 // Replace this subexpr in the parent.
1899 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
1900 return Replacement;
1901}
1902
1903Stmt *RewriteModernObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
1904 if (!SelGetUidFunctionDecl)
1905 SynthSelGetUidFunctionDecl();
1906 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
1907 // Create a call to sel_registerName("selName").
1908 SmallVector<Expr*, 8> SelExprs;
1909 QualType argType = Context->getPointerType(Context->CharTy);
1910 SelExprs.push_back(StringLiteral::Create(*Context,
1911 Exp->getSelector().getAsString(),
1912 StringLiteral::Ascii, false,
1913 argType, SourceLocation()));
1914 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1915 &SelExprs[0], SelExprs.size());
1916 ReplaceStmt(Exp, SelExp);
1917 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
1918 return SelExp;
1919}
1920
1921CallExpr *RewriteModernObjC::SynthesizeCallToFunctionDecl(
1922 FunctionDecl *FD, Expr **args, unsigned nargs, SourceLocation StartLoc,
1923 SourceLocation EndLoc) {
1924 // Get the type, we will need to reference it in a couple spots.
1925 QualType msgSendType = FD->getType();
1926
1927 // Create a reference to the objc_msgSend() declaration.
1928 DeclRefExpr *DRE =
John McCallf4b88a42012-03-10 09:33:50 +00001929 new (Context) DeclRefExpr(FD, false, msgSendType, VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001930
1931 // Now, we cast the reference to a pointer to the objc_msgSend type.
1932 QualType pToFunc = Context->getPointerType(msgSendType);
1933 ImplicitCastExpr *ICE =
1934 ImplicitCastExpr::Create(*Context, pToFunc, CK_FunctionToPointerDecay,
1935 DRE, 0, VK_RValue);
1936
1937 const FunctionType *FT = msgSendType->getAs<FunctionType>();
1938
1939 CallExpr *Exp =
1940 new (Context) CallExpr(*Context, ICE, args, nargs,
1941 FT->getCallResultType(*Context),
1942 VK_RValue, EndLoc);
1943 return Exp;
1944}
1945
1946static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
1947 const char *&startRef, const char *&endRef) {
1948 while (startBuf < endBuf) {
1949 if (*startBuf == '<')
1950 startRef = startBuf; // mark the start.
1951 if (*startBuf == '>') {
1952 if (startRef && *startRef == '<') {
1953 endRef = startBuf; // mark the end.
1954 return true;
1955 }
1956 return false;
1957 }
1958 startBuf++;
1959 }
1960 return false;
1961}
1962
1963static void scanToNextArgument(const char *&argRef) {
1964 int angle = 0;
1965 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
1966 if (*argRef == '<')
1967 angle++;
1968 else if (*argRef == '>')
1969 angle--;
1970 argRef++;
1971 }
1972 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
1973}
1974
1975bool RewriteModernObjC::needToScanForQualifiers(QualType T) {
1976 if (T->isObjCQualifiedIdType())
1977 return true;
1978 if (const PointerType *PT = T->getAs<PointerType>()) {
1979 if (PT->getPointeeType()->isObjCQualifiedIdType())
1980 return true;
1981 }
1982 if (T->isObjCObjectPointerType()) {
1983 T = T->getPointeeType();
1984 return T->isObjCQualifiedInterfaceType();
1985 }
1986 if (T->isArrayType()) {
1987 QualType ElemTy = Context->getBaseElementType(T);
1988 return needToScanForQualifiers(ElemTy);
1989 }
1990 return false;
1991}
1992
1993void RewriteModernObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
1994 QualType Type = E->getType();
1995 if (needToScanForQualifiers(Type)) {
1996 SourceLocation Loc, EndLoc;
1997
1998 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
1999 Loc = ECE->getLParenLoc();
2000 EndLoc = ECE->getRParenLoc();
2001 } else {
2002 Loc = E->getLocStart();
2003 EndLoc = E->getLocEnd();
2004 }
2005 // This will defend against trying to rewrite synthesized expressions.
2006 if (Loc.isInvalid() || EndLoc.isInvalid())
2007 return;
2008
2009 const char *startBuf = SM->getCharacterData(Loc);
2010 const char *endBuf = SM->getCharacterData(EndLoc);
2011 const char *startRef = 0, *endRef = 0;
2012 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2013 // Get the locations of the startRef, endRef.
2014 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-startBuf);
2015 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-startBuf+1);
2016 // Comment out the protocol references.
2017 InsertText(LessLoc, "/*");
2018 InsertText(GreaterLoc, "*/");
2019 }
2020 }
2021}
2022
2023void RewriteModernObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
2024 SourceLocation Loc;
2025 QualType Type;
2026 const FunctionProtoType *proto = 0;
2027 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
2028 Loc = VD->getLocation();
2029 Type = VD->getType();
2030 }
2031 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2032 Loc = FD->getLocation();
2033 // Check for ObjC 'id' and class types that have been adorned with protocol
2034 // information (id<p>, C<p>*). The protocol references need to be rewritten!
2035 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2036 assert(funcType && "missing function type");
2037 proto = dyn_cast<FunctionProtoType>(funcType);
2038 if (!proto)
2039 return;
2040 Type = proto->getResultType();
2041 }
2042 else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2043 Loc = FD->getLocation();
2044 Type = FD->getType();
2045 }
2046 else
2047 return;
2048
2049 if (needToScanForQualifiers(Type)) {
2050 // Since types are unique, we need to scan the buffer.
2051
2052 const char *endBuf = SM->getCharacterData(Loc);
2053 const char *startBuf = endBuf;
2054 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
2055 startBuf--; // scan backward (from the decl location) for return type.
2056 const char *startRef = 0, *endRef = 0;
2057 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2058 // Get the locations of the startRef, endRef.
2059 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-endBuf);
2060 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-endBuf+1);
2061 // Comment out the protocol references.
2062 InsertText(LessLoc, "/*");
2063 InsertText(GreaterLoc, "*/");
2064 }
2065 }
2066 if (!proto)
2067 return; // most likely, was a variable
2068 // Now check arguments.
2069 const char *startBuf = SM->getCharacterData(Loc);
2070 const char *startFuncBuf = startBuf;
2071 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
2072 if (needToScanForQualifiers(proto->getArgType(i))) {
2073 // Since types are unique, we need to scan the buffer.
2074
2075 const char *endBuf = startBuf;
2076 // scan forward (from the decl location) for argument types.
2077 scanToNextArgument(endBuf);
2078 const char *startRef = 0, *endRef = 0;
2079 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2080 // Get the locations of the startRef, endRef.
2081 SourceLocation LessLoc =
2082 Loc.getLocWithOffset(startRef-startFuncBuf);
2083 SourceLocation GreaterLoc =
2084 Loc.getLocWithOffset(endRef-startFuncBuf+1);
2085 // Comment out the protocol references.
2086 InsertText(LessLoc, "/*");
2087 InsertText(GreaterLoc, "*/");
2088 }
2089 startBuf = ++endBuf;
2090 }
2091 else {
2092 // If the function name is derived from a macro expansion, then the
2093 // argument buffer will not follow the name. Need to speak with Chris.
2094 while (*startBuf && *startBuf != ')' && *startBuf != ',')
2095 startBuf++; // scan forward (from the decl location) for argument types.
2096 startBuf++;
2097 }
2098 }
2099}
2100
2101void RewriteModernObjC::RewriteTypeOfDecl(VarDecl *ND) {
2102 QualType QT = ND->getType();
2103 const Type* TypePtr = QT->getAs<Type>();
2104 if (!isa<TypeOfExprType>(TypePtr))
2105 return;
2106 while (isa<TypeOfExprType>(TypePtr)) {
2107 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
2108 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
2109 TypePtr = QT->getAs<Type>();
2110 }
2111 // FIXME. This will not work for multiple declarators; as in:
2112 // __typeof__(a) b,c,d;
2113 std::string TypeAsString(QT.getAsString(Context->getPrintingPolicy()));
2114 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
2115 const char *startBuf = SM->getCharacterData(DeclLoc);
2116 if (ND->getInit()) {
2117 std::string Name(ND->getNameAsString());
2118 TypeAsString += " " + Name + " = ";
2119 Expr *E = ND->getInit();
2120 SourceLocation startLoc;
2121 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
2122 startLoc = ECE->getLParenLoc();
2123 else
2124 startLoc = E->getLocStart();
2125 startLoc = SM->getExpansionLoc(startLoc);
2126 const char *endBuf = SM->getCharacterData(startLoc);
2127 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2128 }
2129 else {
2130 SourceLocation X = ND->getLocEnd();
2131 X = SM->getExpansionLoc(X);
2132 const char *endBuf = SM->getCharacterData(X);
2133 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2134 }
2135}
2136
2137// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
2138void RewriteModernObjC::SynthSelGetUidFunctionDecl() {
2139 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
2140 SmallVector<QualType, 16> ArgTys;
2141 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2142 QualType getFuncType =
2143 getSimpleFunctionType(Context->getObjCSelType(), &ArgTys[0], ArgTys.size());
2144 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2145 SourceLocation(),
2146 SourceLocation(),
2147 SelGetUidIdent, getFuncType, 0,
2148 SC_Extern,
2149 SC_None, false);
2150}
2151
2152void RewriteModernObjC::RewriteFunctionDecl(FunctionDecl *FD) {
2153 // declared in <objc/objc.h>
2154 if (FD->getIdentifier() &&
2155 FD->getName() == "sel_registerName") {
2156 SelGetUidFunctionDecl = FD;
2157 return;
2158 }
2159 RewriteObjCQualifiedInterfaceTypes(FD);
2160}
2161
2162void RewriteModernObjC::RewriteBlockPointerType(std::string& Str, QualType Type) {
2163 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
2164 const char *argPtr = TypeString.c_str();
2165 if (!strchr(argPtr, '^')) {
2166 Str += TypeString;
2167 return;
2168 }
2169 while (*argPtr) {
2170 Str += (*argPtr == '^' ? '*' : *argPtr);
2171 argPtr++;
2172 }
2173}
2174
2175// FIXME. Consolidate this routine with RewriteBlockPointerType.
2176void RewriteModernObjC::RewriteBlockPointerTypeVariable(std::string& Str,
2177 ValueDecl *VD) {
2178 QualType Type = VD->getType();
2179 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
2180 const char *argPtr = TypeString.c_str();
2181 int paren = 0;
2182 while (*argPtr) {
2183 switch (*argPtr) {
2184 case '(':
2185 Str += *argPtr;
2186 paren++;
2187 break;
2188 case ')':
2189 Str += *argPtr;
2190 paren--;
2191 break;
2192 case '^':
2193 Str += '*';
2194 if (paren == 1)
2195 Str += VD->getNameAsString();
2196 break;
2197 default:
2198 Str += *argPtr;
2199 break;
2200 }
2201 argPtr++;
2202 }
2203}
2204
2205
2206void RewriteModernObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) {
2207 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
2208 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2209 const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(funcType);
2210 if (!proto)
2211 return;
2212 QualType Type = proto->getResultType();
2213 std::string FdStr = Type.getAsString(Context->getPrintingPolicy());
2214 FdStr += " ";
2215 FdStr += FD->getName();
2216 FdStr += "(";
2217 unsigned numArgs = proto->getNumArgs();
2218 for (unsigned i = 0; i < numArgs; i++) {
2219 QualType ArgType = proto->getArgType(i);
2220 RewriteBlockPointerType(FdStr, ArgType);
2221 if (i+1 < numArgs)
2222 FdStr += ", ";
2223 }
2224 FdStr += ");\n";
2225 InsertText(FunLocStart, FdStr);
2226 CurFunctionDeclToDeclareForBlock = 0;
2227}
2228
2229// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
2230void RewriteModernObjC::SynthSuperContructorFunctionDecl() {
2231 if (SuperContructorFunctionDecl)
2232 return;
2233 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
2234 SmallVector<QualType, 16> ArgTys;
2235 QualType argT = Context->getObjCIdType();
2236 assert(!argT.isNull() && "Can't find 'id' type");
2237 ArgTys.push_back(argT);
2238 ArgTys.push_back(argT);
2239 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2240 &ArgTys[0], ArgTys.size());
2241 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2242 SourceLocation(),
2243 SourceLocation(),
2244 msgSendIdent, msgSendType, 0,
2245 SC_Extern,
2246 SC_None, false);
2247}
2248
2249// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
2250void RewriteModernObjC::SynthMsgSendFunctionDecl() {
2251 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
2252 SmallVector<QualType, 16> ArgTys;
2253 QualType argT = Context->getObjCIdType();
2254 assert(!argT.isNull() && "Can't find 'id' type");
2255 ArgTys.push_back(argT);
2256 argT = Context->getObjCSelType();
2257 assert(!argT.isNull() && "Can't find 'SEL' type");
2258 ArgTys.push_back(argT);
2259 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2260 &ArgTys[0], ArgTys.size(),
2261 true /*isVariadic*/);
2262 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2263 SourceLocation(),
2264 SourceLocation(),
2265 msgSendIdent, msgSendType, 0,
2266 SC_Extern,
2267 SC_None, false);
2268}
2269
2270// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
2271void RewriteModernObjC::SynthMsgSendSuperFunctionDecl() {
2272 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
2273 SmallVector<QualType, 16> ArgTys;
2274 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
2275 SourceLocation(), SourceLocation(),
2276 &Context->Idents.get("objc_super"));
2277 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2278 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2279 ArgTys.push_back(argT);
2280 argT = Context->getObjCSelType();
2281 assert(!argT.isNull() && "Can't find 'SEL' type");
2282 ArgTys.push_back(argT);
2283 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2284 &ArgTys[0], ArgTys.size(),
2285 true /*isVariadic*/);
2286 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2287 SourceLocation(),
2288 SourceLocation(),
2289 msgSendIdent, msgSendType, 0,
2290 SC_Extern,
2291 SC_None, false);
2292}
2293
2294// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
2295void RewriteModernObjC::SynthMsgSendStretFunctionDecl() {
2296 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
2297 SmallVector<QualType, 16> ArgTys;
2298 QualType argT = Context->getObjCIdType();
2299 assert(!argT.isNull() && "Can't find 'id' type");
2300 ArgTys.push_back(argT);
2301 argT = Context->getObjCSelType();
2302 assert(!argT.isNull() && "Can't find 'SEL' type");
2303 ArgTys.push_back(argT);
2304 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2305 &ArgTys[0], ArgTys.size(),
2306 true /*isVariadic*/);
2307 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2308 SourceLocation(),
2309 SourceLocation(),
2310 msgSendIdent, msgSendType, 0,
2311 SC_Extern,
2312 SC_None, false);
2313}
2314
2315// SynthMsgSendSuperStretFunctionDecl -
2316// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
2317void RewriteModernObjC::SynthMsgSendSuperStretFunctionDecl() {
2318 IdentifierInfo *msgSendIdent =
2319 &Context->Idents.get("objc_msgSendSuper_stret");
2320 SmallVector<QualType, 16> ArgTys;
2321 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
2322 SourceLocation(), SourceLocation(),
2323 &Context->Idents.get("objc_super"));
2324 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2325 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2326 ArgTys.push_back(argT);
2327 argT = Context->getObjCSelType();
2328 assert(!argT.isNull() && "Can't find 'SEL' type");
2329 ArgTys.push_back(argT);
2330 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2331 &ArgTys[0], ArgTys.size(),
2332 true /*isVariadic*/);
2333 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2334 SourceLocation(),
2335 SourceLocation(),
2336 msgSendIdent, msgSendType, 0,
2337 SC_Extern,
2338 SC_None, false);
2339}
2340
2341// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
2342void RewriteModernObjC::SynthMsgSendFpretFunctionDecl() {
2343 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2344 SmallVector<QualType, 16> ArgTys;
2345 QualType argT = Context->getObjCIdType();
2346 assert(!argT.isNull() && "Can't find 'id' type");
2347 ArgTys.push_back(argT);
2348 argT = Context->getObjCSelType();
2349 assert(!argT.isNull() && "Can't find 'SEL' type");
2350 ArgTys.push_back(argT);
2351 QualType msgSendType = getSimpleFunctionType(Context->DoubleTy,
2352 &ArgTys[0], ArgTys.size(),
2353 true /*isVariadic*/);
2354 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2355 SourceLocation(),
2356 SourceLocation(),
2357 msgSendIdent, msgSendType, 0,
2358 SC_Extern,
2359 SC_None, false);
2360}
2361
2362// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
2363void RewriteModernObjC::SynthGetClassFunctionDecl() {
2364 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
2365 SmallVector<QualType, 16> ArgTys;
2366 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2367 QualType getClassType = getSimpleFunctionType(Context->getObjCIdType(),
2368 &ArgTys[0], ArgTys.size());
2369 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2370 SourceLocation(),
2371 SourceLocation(),
2372 getClassIdent, getClassType, 0,
2373 SC_Extern,
2374 SC_None, false);
2375}
2376
2377// SynthGetSuperClassFunctionDecl - Class class_getSuperclass(Class cls);
2378void RewriteModernObjC::SynthGetSuperClassFunctionDecl() {
2379 IdentifierInfo *getSuperClassIdent =
2380 &Context->Idents.get("class_getSuperclass");
2381 SmallVector<QualType, 16> ArgTys;
2382 ArgTys.push_back(Context->getObjCClassType());
2383 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
2384 &ArgTys[0], ArgTys.size());
2385 GetSuperClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2386 SourceLocation(),
2387 SourceLocation(),
2388 getSuperClassIdent,
2389 getClassType, 0,
2390 SC_Extern,
2391 SC_None,
2392 false);
2393}
2394
2395// SynthGetMetaClassFunctionDecl - id objc_getMetaClass(const char *name);
2396void RewriteModernObjC::SynthGetMetaClassFunctionDecl() {
2397 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2398 SmallVector<QualType, 16> ArgTys;
2399 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2400 QualType getClassType = getSimpleFunctionType(Context->getObjCIdType(),
2401 &ArgTys[0], ArgTys.size());
2402 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2403 SourceLocation(),
2404 SourceLocation(),
2405 getClassIdent, getClassType, 0,
2406 SC_Extern,
2407 SC_None, false);
2408}
2409
2410Stmt *RewriteModernObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
2411 QualType strType = getConstantStringStructType();
2412
2413 std::string S = "__NSConstantStringImpl_";
2414
2415 std::string tmpName = InFileName;
2416 unsigned i;
2417 for (i=0; i < tmpName.length(); i++) {
2418 char c = tmpName.at(i);
2419 // replace any non alphanumeric characters with '_'.
2420 if (!isalpha(c) && (c < '0' || c > '9'))
2421 tmpName[i] = '_';
2422 }
2423 S += tmpName;
2424 S += "_";
2425 S += utostr(NumObjCStringLiterals++);
2426
2427 Preamble += "static __NSConstantStringImpl " + S;
2428 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2429 Preamble += "0x000007c8,"; // utf8_str
2430 // The pretty printer for StringLiteral handles escape characters properly.
2431 std::string prettyBufS;
2432 llvm::raw_string_ostream prettyBuf(prettyBufS);
2433 Exp->getString()->printPretty(prettyBuf, *Context, 0,
2434 PrintingPolicy(LangOpts));
2435 Preamble += prettyBuf.str();
2436 Preamble += ",";
2437 Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
2438
2439 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
2440 SourceLocation(), &Context->Idents.get(S),
2441 strType, 0, SC_Static, SC_None);
John McCallf4b88a42012-03-10 09:33:50 +00002442 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, false, strType, VK_LValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002443 SourceLocation());
2444 Expr *Unop = new (Context) UnaryOperator(DRE, UO_AddrOf,
2445 Context->getPointerType(DRE->getType()),
2446 VK_RValue, OK_Ordinary,
2447 SourceLocation());
2448 // cast to NSConstantString *
2449 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(),
2450 CK_CPointerToObjCPointerCast, Unop);
2451 ReplaceStmt(Exp, cast);
2452 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2453 return cast;
2454}
2455
2456// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
2457QualType RewriteModernObjC::getSuperStructType() {
2458 if (!SuperStructDecl) {
2459 SuperStructDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
2460 SourceLocation(), SourceLocation(),
2461 &Context->Idents.get("objc_super"));
2462 QualType FieldTypes[2];
2463
2464 // struct objc_object *receiver;
2465 FieldTypes[0] = Context->getObjCIdType();
2466 // struct objc_class *super;
2467 FieldTypes[1] = Context->getObjCClassType();
2468
2469 // Create fields
2470 for (unsigned i = 0; i < 2; ++i) {
2471 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
2472 SourceLocation(),
2473 SourceLocation(), 0,
2474 FieldTypes[i], 0,
2475 /*BitWidth=*/0,
2476 /*Mutable=*/false,
2477 /*HasInit=*/false));
2478 }
2479
2480 SuperStructDecl->completeDefinition();
2481 }
2482 return Context->getTagDeclType(SuperStructDecl);
2483}
2484
2485QualType RewriteModernObjC::getConstantStringStructType() {
2486 if (!ConstantStringDecl) {
2487 ConstantStringDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
2488 SourceLocation(), SourceLocation(),
2489 &Context->Idents.get("__NSConstantStringImpl"));
2490 QualType FieldTypes[4];
2491
2492 // struct objc_object *receiver;
2493 FieldTypes[0] = Context->getObjCIdType();
2494 // int flags;
2495 FieldTypes[1] = Context->IntTy;
2496 // char *str;
2497 FieldTypes[2] = Context->getPointerType(Context->CharTy);
2498 // long length;
2499 FieldTypes[3] = Context->LongTy;
2500
2501 // Create fields
2502 for (unsigned i = 0; i < 4; ++i) {
2503 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
2504 ConstantStringDecl,
2505 SourceLocation(),
2506 SourceLocation(), 0,
2507 FieldTypes[i], 0,
2508 /*BitWidth=*/0,
2509 /*Mutable=*/true,
2510 /*HasInit=*/false));
2511 }
2512
2513 ConstantStringDecl->completeDefinition();
2514 }
2515 return Context->getTagDeclType(ConstantStringDecl);
2516}
2517
2518Stmt *RewriteModernObjC::SynthMessageExpr(ObjCMessageExpr *Exp,
2519 SourceLocation StartLoc,
2520 SourceLocation EndLoc) {
2521 if (!SelGetUidFunctionDecl)
2522 SynthSelGetUidFunctionDecl();
2523 if (!MsgSendFunctionDecl)
2524 SynthMsgSendFunctionDecl();
2525 if (!MsgSendSuperFunctionDecl)
2526 SynthMsgSendSuperFunctionDecl();
2527 if (!MsgSendStretFunctionDecl)
2528 SynthMsgSendStretFunctionDecl();
2529 if (!MsgSendSuperStretFunctionDecl)
2530 SynthMsgSendSuperStretFunctionDecl();
2531 if (!MsgSendFpretFunctionDecl)
2532 SynthMsgSendFpretFunctionDecl();
2533 if (!GetClassFunctionDecl)
2534 SynthGetClassFunctionDecl();
2535 if (!GetSuperClassFunctionDecl)
2536 SynthGetSuperClassFunctionDecl();
2537 if (!GetMetaClassFunctionDecl)
2538 SynthGetMetaClassFunctionDecl();
2539
2540 // default to objc_msgSend().
2541 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2542 // May need to use objc_msgSend_stret() as well.
2543 FunctionDecl *MsgSendStretFlavor = 0;
2544 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
2545 QualType resultType = mDecl->getResultType();
2546 if (resultType->isRecordType())
2547 MsgSendStretFlavor = MsgSendStretFunctionDecl;
2548 else if (resultType->isRealFloatingType())
2549 MsgSendFlavor = MsgSendFpretFunctionDecl;
2550 }
2551
2552 // Synthesize a call to objc_msgSend().
2553 SmallVector<Expr*, 8> MsgExprs;
2554 switch (Exp->getReceiverKind()) {
2555 case ObjCMessageExpr::SuperClass: {
2556 MsgSendFlavor = MsgSendSuperFunctionDecl;
2557 if (MsgSendStretFlavor)
2558 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2559 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2560
2561 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
2562
2563 SmallVector<Expr*, 4> InitExprs;
2564
2565 // set the receiver to self, the first argument to all methods.
2566 InitExprs.push_back(
2567 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2568 CK_BitCast,
2569 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCallf4b88a42012-03-10 09:33:50 +00002570 false,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002571 Context->getObjCIdType(),
2572 VK_RValue,
2573 SourceLocation()))
2574 ); // set the 'receiver'.
2575
2576 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2577 SmallVector<Expr*, 8> ClsExprs;
2578 QualType argType = Context->getPointerType(Context->CharTy);
2579 ClsExprs.push_back(StringLiteral::Create(*Context,
2580 ClassDecl->getIdentifier()->getName(),
2581 StringLiteral::Ascii, false,
2582 argType, SourceLocation()));
2583 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
2584 &ClsExprs[0],
2585 ClsExprs.size(),
2586 StartLoc,
2587 EndLoc);
2588 // (Class)objc_getClass("CurrentClass")
2589 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2590 Context->getObjCClassType(),
2591 CK_BitCast, Cls);
2592 ClsExprs.clear();
2593 ClsExprs.push_back(ArgExpr);
2594 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
2595 &ClsExprs[0], ClsExprs.size(),
2596 StartLoc, EndLoc);
2597
2598 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2599 // To turn off a warning, type-cast to 'id'
2600 InitExprs.push_back( // set 'super class', using class_getSuperclass().
2601 NoTypeInfoCStyleCastExpr(Context,
2602 Context->getObjCIdType(),
2603 CK_BitCast, Cls));
2604 // struct objc_super
2605 QualType superType = getSuperStructType();
2606 Expr *SuperRep;
2607
2608 if (LangOpts.MicrosoftExt) {
2609 SynthSuperContructorFunctionDecl();
2610 // Simulate a contructor call...
2611 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
John McCallf4b88a42012-03-10 09:33:50 +00002612 false, superType, VK_LValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002613 SourceLocation());
2614 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
2615 InitExprs.size(),
2616 superType, VK_LValue,
2617 SourceLocation());
2618 // The code for super is a little tricky to prevent collision with
2619 // the structure definition in the header. The rewriter has it's own
2620 // internal definition (__rw_objc_super) that is uses. This is why
2621 // we need the cast below. For example:
2622 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2623 //
2624 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
2625 Context->getPointerType(SuperRep->getType()),
2626 VK_RValue, OK_Ordinary,
2627 SourceLocation());
2628 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2629 Context->getPointerType(superType),
2630 CK_BitCast, SuperRep);
2631 } else {
2632 // (struct objc_super) { <exprs from above> }
2633 InitListExpr *ILE =
2634 new (Context) InitListExpr(*Context, SourceLocation(),
2635 &InitExprs[0], InitExprs.size(),
2636 SourceLocation());
2637 TypeSourceInfo *superTInfo
2638 = Context->getTrivialTypeSourceInfo(superType);
2639 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
2640 superType, VK_LValue,
2641 ILE, false);
2642 // struct objc_super *
2643 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
2644 Context->getPointerType(SuperRep->getType()),
2645 VK_RValue, OK_Ordinary,
2646 SourceLocation());
2647 }
2648 MsgExprs.push_back(SuperRep);
2649 break;
2650 }
2651
2652 case ObjCMessageExpr::Class: {
2653 SmallVector<Expr*, 8> ClsExprs;
2654 QualType argType = Context->getPointerType(Context->CharTy);
2655 ObjCInterfaceDecl *Class
2656 = Exp->getClassReceiver()->getAs<ObjCObjectType>()->getInterface();
2657 IdentifierInfo *clsName = Class->getIdentifier();
2658 ClsExprs.push_back(StringLiteral::Create(*Context,
2659 clsName->getName(),
2660 StringLiteral::Ascii, false,
2661 argType, SourceLocation()));
2662 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2663 &ClsExprs[0],
2664 ClsExprs.size(),
2665 StartLoc, EndLoc);
2666 MsgExprs.push_back(Cls);
2667 break;
2668 }
2669
2670 case ObjCMessageExpr::SuperInstance:{
2671 MsgSendFlavor = MsgSendSuperFunctionDecl;
2672 if (MsgSendStretFlavor)
2673 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2674 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2675 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
2676 SmallVector<Expr*, 4> InitExprs;
2677
2678 InitExprs.push_back(
2679 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2680 CK_BitCast,
2681 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCallf4b88a42012-03-10 09:33:50 +00002682 false,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002683 Context->getObjCIdType(),
2684 VK_RValue, SourceLocation()))
2685 ); // set the 'receiver'.
2686
2687 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2688 SmallVector<Expr*, 8> ClsExprs;
2689 QualType argType = Context->getPointerType(Context->CharTy);
2690 ClsExprs.push_back(StringLiteral::Create(*Context,
2691 ClassDecl->getIdentifier()->getName(),
2692 StringLiteral::Ascii, false, argType,
2693 SourceLocation()));
2694 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2695 &ClsExprs[0],
2696 ClsExprs.size(),
2697 StartLoc, EndLoc);
2698 // (Class)objc_getClass("CurrentClass")
2699 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2700 Context->getObjCClassType(),
2701 CK_BitCast, Cls);
2702 ClsExprs.clear();
2703 ClsExprs.push_back(ArgExpr);
2704 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
2705 &ClsExprs[0], ClsExprs.size(),
2706 StartLoc, EndLoc);
2707
2708 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2709 // To turn off a warning, type-cast to 'id'
2710 InitExprs.push_back(
2711 // set 'super class', using class_getSuperclass().
2712 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2713 CK_BitCast, Cls));
2714 // struct objc_super
2715 QualType superType = getSuperStructType();
2716 Expr *SuperRep;
2717
2718 if (LangOpts.MicrosoftExt) {
2719 SynthSuperContructorFunctionDecl();
2720 // Simulate a contructor call...
2721 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
John McCallf4b88a42012-03-10 09:33:50 +00002722 false, superType, VK_LValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002723 SourceLocation());
2724 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
2725 InitExprs.size(),
2726 superType, VK_LValue, SourceLocation());
2727 // The code for super is a little tricky to prevent collision with
2728 // the structure definition in the header. The rewriter has it's own
2729 // internal definition (__rw_objc_super) that is uses. This is why
2730 // we need the cast below. For example:
2731 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2732 //
2733 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
2734 Context->getPointerType(SuperRep->getType()),
2735 VK_RValue, OK_Ordinary,
2736 SourceLocation());
2737 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2738 Context->getPointerType(superType),
2739 CK_BitCast, SuperRep);
2740 } else {
2741 // (struct objc_super) { <exprs from above> }
2742 InitListExpr *ILE =
2743 new (Context) InitListExpr(*Context, SourceLocation(),
2744 &InitExprs[0], InitExprs.size(),
2745 SourceLocation());
2746 TypeSourceInfo *superTInfo
2747 = Context->getTrivialTypeSourceInfo(superType);
2748 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
2749 superType, VK_RValue, ILE,
2750 false);
2751 }
2752 MsgExprs.push_back(SuperRep);
2753 break;
2754 }
2755
2756 case ObjCMessageExpr::Instance: {
2757 // Remove all type-casts because it may contain objc-style types; e.g.
2758 // Foo<Proto> *.
2759 Expr *recExpr = Exp->getInstanceReceiver();
2760 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
2761 recExpr = CE->getSubExpr();
2762 CastKind CK = recExpr->getType()->isObjCObjectPointerType()
2763 ? CK_BitCast : recExpr->getType()->isBlockPointerType()
2764 ? CK_BlockPointerToObjCPointerCast
2765 : CK_CPointerToObjCPointerCast;
2766
2767 recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2768 CK, recExpr);
2769 MsgExprs.push_back(recExpr);
2770 break;
2771 }
2772 }
2773
2774 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
2775 SmallVector<Expr*, 8> SelExprs;
2776 QualType argType = Context->getPointerType(Context->CharTy);
2777 SelExprs.push_back(StringLiteral::Create(*Context,
2778 Exp->getSelector().getAsString(),
2779 StringLiteral::Ascii, false,
2780 argType, SourceLocation()));
2781 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2782 &SelExprs[0], SelExprs.size(),
2783 StartLoc,
2784 EndLoc);
2785 MsgExprs.push_back(SelExp);
2786
2787 // Now push any user supplied arguments.
2788 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
2789 Expr *userExpr = Exp->getArg(i);
2790 // Make all implicit casts explicit...ICE comes in handy:-)
2791 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2792 // Reuse the ICE type, it is exactly what the doctor ordered.
2793 QualType type = ICE->getType();
2794 if (needToScanForQualifiers(type))
2795 type = Context->getObjCIdType();
2796 // Make sure we convert "type (^)(...)" to "type (*)(...)".
2797 (void)convertBlockPointerToFunctionPointer(type);
2798 const Expr *SubExpr = ICE->IgnoreParenImpCasts();
2799 CastKind CK;
2800 if (SubExpr->getType()->isIntegralType(*Context) &&
2801 type->isBooleanType()) {
2802 CK = CK_IntegralToBoolean;
2803 } else if (type->isObjCObjectPointerType()) {
2804 if (SubExpr->getType()->isBlockPointerType()) {
2805 CK = CK_BlockPointerToObjCPointerCast;
2806 } else if (SubExpr->getType()->isPointerType()) {
2807 CK = CK_CPointerToObjCPointerCast;
2808 } else {
2809 CK = CK_BitCast;
2810 }
2811 } else {
2812 CK = CK_BitCast;
2813 }
2814
2815 userExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, userExpr);
2816 }
2817 // Make id<P...> cast into an 'id' cast.
2818 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
2819 if (CE->getType()->isObjCQualifiedIdType()) {
2820 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
2821 userExpr = CE->getSubExpr();
2822 CastKind CK;
2823 if (userExpr->getType()->isIntegralType(*Context)) {
2824 CK = CK_IntegralToPointer;
2825 } else if (userExpr->getType()->isBlockPointerType()) {
2826 CK = CK_BlockPointerToObjCPointerCast;
2827 } else if (userExpr->getType()->isPointerType()) {
2828 CK = CK_CPointerToObjCPointerCast;
2829 } else {
2830 CK = CK_BitCast;
2831 }
2832 userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2833 CK, userExpr);
2834 }
2835 }
2836 MsgExprs.push_back(userExpr);
2837 // We've transferred the ownership to MsgExprs. For now, we *don't* null
2838 // out the argument in the original expression (since we aren't deleting
2839 // the ObjCMessageExpr). See RewritePropertyOrImplicitSetter() usage for more info.
2840 //Exp->setArg(i, 0);
2841 }
2842 // Generate the funky cast.
2843 CastExpr *cast;
2844 SmallVector<QualType, 8> ArgTypes;
2845 QualType returnType;
2846
2847 // Push 'id' and 'SEL', the 2 implicit arguments.
2848 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
2849 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
2850 else
2851 ArgTypes.push_back(Context->getObjCIdType());
2852 ArgTypes.push_back(Context->getObjCSelType());
2853 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
2854 // Push any user argument types.
2855 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
2856 E = OMD->param_end(); PI != E; ++PI) {
2857 QualType t = (*PI)->getType()->isObjCQualifiedIdType()
2858 ? Context->getObjCIdType()
2859 : (*PI)->getType();
2860 // Make sure we convert "t (^)(...)" to "t (*)(...)".
2861 (void)convertBlockPointerToFunctionPointer(t);
2862 ArgTypes.push_back(t);
2863 }
2864 returnType = Exp->getType();
2865 convertToUnqualifiedObjCType(returnType);
2866 (void)convertBlockPointerToFunctionPointer(returnType);
2867 } else {
2868 returnType = Context->getObjCIdType();
2869 }
2870 // Get the type, we will need to reference it in a couple spots.
2871 QualType msgSendType = MsgSendFlavor->getType();
2872
2873 // Create a reference to the objc_msgSend() declaration.
John McCallf4b88a42012-03-10 09:33:50 +00002874 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002875 VK_LValue, SourceLocation());
2876
2877 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
2878 // If we don't do this cast, we get the following bizarre warning/note:
2879 // xx.m:13: warning: function called through a non-compatible type
2880 // xx.m:13: note: if this code is reached, the program will abort
2881 cast = NoTypeInfoCStyleCastExpr(Context,
2882 Context->getPointerType(Context->VoidTy),
2883 CK_BitCast, DRE);
2884
2885 // Now do the "normal" pointer to function cast.
2886 QualType castType =
2887 getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
2888 // If we don't have a method decl, force a variadic cast.
2889 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true);
2890 castType = Context->getPointerType(castType);
2891 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2892 cast);
2893
2894 // Don't forget the parens to enforce the proper binding.
2895 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
2896
2897 const FunctionType *FT = msgSendType->getAs<FunctionType>();
2898 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
2899 MsgExprs.size(),
2900 FT->getResultType(), VK_RValue,
2901 EndLoc);
2902 Stmt *ReplacingStmt = CE;
2903 if (MsgSendStretFlavor) {
2904 // We have the method which returns a struct/union. Must also generate
2905 // call to objc_msgSend_stret and hang both varieties on a conditional
2906 // expression which dictate which one to envoke depending on size of
2907 // method's return type.
2908
2909 // Create a reference to the objc_msgSend_stret() declaration.
John McCallf4b88a42012-03-10 09:33:50 +00002910 DeclRefExpr *STDRE = new (Context) DeclRefExpr(MsgSendStretFlavor,
2911 false, msgSendType,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002912 VK_LValue, SourceLocation());
2913 // Need to cast objc_msgSend_stret to "void *" (see above comment).
2914 cast = NoTypeInfoCStyleCastExpr(Context,
2915 Context->getPointerType(Context->VoidTy),
2916 CK_BitCast, STDRE);
2917 // Now do the "normal" pointer to function cast.
2918 castType = getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
2919 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false);
2920 castType = Context->getPointerType(castType);
2921 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2922 cast);
2923
2924 // Don't forget the parens to enforce the proper binding.
2925 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
2926
2927 FT = msgSendType->getAs<FunctionType>();
2928 CallExpr *STCE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
2929 MsgExprs.size(),
2930 FT->getResultType(), VK_RValue,
2931 SourceLocation());
2932
2933 // Build sizeof(returnType)
2934 UnaryExprOrTypeTraitExpr *sizeofExpr =
2935 new (Context) UnaryExprOrTypeTraitExpr(UETT_SizeOf,
2936 Context->getTrivialTypeSourceInfo(returnType),
2937 Context->getSizeType(), SourceLocation(),
2938 SourceLocation());
2939 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2940 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
2941 // For X86 it is more complicated and some kind of target specific routine
2942 // is needed to decide what to do.
2943 unsigned IntSize =
2944 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
2945 IntegerLiteral *limit = IntegerLiteral::Create(*Context,
2946 llvm::APInt(IntSize, 8),
2947 Context->IntTy,
2948 SourceLocation());
2949 BinaryOperator *lessThanExpr =
2950 new (Context) BinaryOperator(sizeofExpr, limit, BO_LE, Context->IntTy,
2951 VK_RValue, OK_Ordinary, SourceLocation());
2952 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2953 ConditionalOperator *CondExpr =
2954 new (Context) ConditionalOperator(lessThanExpr,
2955 SourceLocation(), CE,
2956 SourceLocation(), STCE,
2957 returnType, VK_RValue, OK_Ordinary);
2958 ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
2959 CondExpr);
2960 }
2961 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2962 return ReplacingStmt;
2963}
2964
2965Stmt *RewriteModernObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
2966 Stmt *ReplacingStmt = SynthMessageExpr(Exp, Exp->getLocStart(),
2967 Exp->getLocEnd());
2968
2969 // Now do the actual rewrite.
2970 ReplaceStmt(Exp, ReplacingStmt);
2971
2972 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2973 return ReplacingStmt;
2974}
2975
2976// typedef struct objc_object Protocol;
2977QualType RewriteModernObjC::getProtocolType() {
2978 if (!ProtocolTypeDecl) {
2979 TypeSourceInfo *TInfo
2980 = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
2981 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
2982 SourceLocation(), SourceLocation(),
2983 &Context->Idents.get("Protocol"),
2984 TInfo);
2985 }
2986 return Context->getTypeDeclType(ProtocolTypeDecl);
2987}
2988
2989/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
2990/// a synthesized/forward data reference (to the protocol's metadata).
2991/// The forward references (and metadata) are generated in
2992/// RewriteModernObjC::HandleTranslationUnit().
2993Stmt *RewriteModernObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
2994 std::string Name = "_OBJC_PROTOCOL_" + Exp->getProtocol()->getNameAsString();
2995 IdentifierInfo *ID = &Context->Idents.get(Name);
2996 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
2997 SourceLocation(), ID, getProtocolType(), 0,
2998 SC_Extern, SC_None);
John McCallf4b88a42012-03-10 09:33:50 +00002999 DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, false, getProtocolType(),
3000 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003001 Expr *DerefExpr = new (Context) UnaryOperator(DRE, UO_AddrOf,
3002 Context->getPointerType(DRE->getType()),
3003 VK_RValue, OK_Ordinary, SourceLocation());
3004 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, DerefExpr->getType(),
3005 CK_BitCast,
3006 DerefExpr);
3007 ReplaceStmt(Exp, castExpr);
3008 ProtocolExprDecls.insert(Exp->getProtocol()->getCanonicalDecl());
3009 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3010 return castExpr;
3011
3012}
3013
3014bool RewriteModernObjC::BufferContainsPPDirectives(const char *startBuf,
3015 const char *endBuf) {
3016 while (startBuf < endBuf) {
3017 if (*startBuf == '#') {
3018 // Skip whitespace.
3019 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
3020 ;
3021 if (!strncmp(startBuf, "if", strlen("if")) ||
3022 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
3023 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
3024 !strncmp(startBuf, "define", strlen("define")) ||
3025 !strncmp(startBuf, "undef", strlen("undef")) ||
3026 !strncmp(startBuf, "else", strlen("else")) ||
3027 !strncmp(startBuf, "elif", strlen("elif")) ||
3028 !strncmp(startBuf, "endif", strlen("endif")) ||
3029 !strncmp(startBuf, "pragma", strlen("pragma")) ||
3030 !strncmp(startBuf, "include", strlen("include")) ||
3031 !strncmp(startBuf, "import", strlen("import")) ||
3032 !strncmp(startBuf, "include_next", strlen("include_next")))
3033 return true;
3034 }
3035 startBuf++;
3036 }
3037 return false;
3038}
3039
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003040/// RewriteObjCFieldDeclType - This routine rewrites a type into the buffer.
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003041/// It handles elaborated types, as well as enum types in the process.
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003042bool RewriteModernObjC::RewriteObjCFieldDeclType(QualType &Type,
3043 std::string &Result) {
3044 if (Type->isArrayType()) {
3045 QualType ElemTy = Context->getBaseElementType(Type);
3046 return RewriteObjCFieldDeclType(ElemTy, Result);
3047 }
3048 else if (Type->isRecordType()) {
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003049 RecordDecl *RD = Type->getAs<RecordType>()->getDecl();
3050 if (RD->isCompleteDefinition()) {
3051 if (RD->isStruct())
3052 Result += "\n\tstruct ";
3053 else if (RD->isUnion())
3054 Result += "\n\tunion ";
3055 else
3056 assert(false && "class not allowed as an ivar type");
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003057
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003058 Result += RD->getName();
3059 if (TagsDefinedInIvarDecls.count(RD)) {
3060 // This struct is already defined. Do not write its definition again.
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003061 Result += " ";
3062 return true;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003063 }
3064 TagsDefinedInIvarDecls.insert(RD);
3065 Result += " {\n";
3066 for (RecordDecl::field_iterator i = RD->field_begin(),
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003067 e = RD->field_end(); i != e; ++i) {
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003068 FieldDecl *FD = *i;
3069 RewriteObjCFieldDecl(FD, Result);
3070 }
3071 Result += "\t} ";
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003072 return true;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003073 }
3074 }
3075 else if (Type->isEnumeralType()) {
3076 EnumDecl *ED = Type->getAs<EnumType>()->getDecl();
3077 if (ED->isCompleteDefinition()) {
3078 Result += "\n\tenum ";
3079 Result += ED->getName();
3080 if (TagsDefinedInIvarDecls.count(ED)) {
3081 // This enum is already defined. Do not write its definition again.
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003082 Result += " ";
3083 return true;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003084 }
3085 TagsDefinedInIvarDecls.insert(ED);
3086
3087 Result += " {\n";
3088 for (EnumDecl::enumerator_iterator EC = ED->enumerator_begin(),
3089 ECEnd = ED->enumerator_end(); EC != ECEnd; ++EC) {
3090 Result += "\t"; Result += EC->getName(); Result += " = ";
3091 llvm::APSInt Val = EC->getInitVal();
3092 Result += Val.toString(10);
3093 Result += ",\n";
3094 }
3095 Result += "\t} ";
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003096 return true;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003097 }
3098 }
3099
3100 Result += "\t";
3101 convertObjCTypeToCStyleType(Type);
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003102 return false;
3103}
3104
3105
3106/// RewriteObjCFieldDecl - This routine rewrites a field into the buffer.
3107/// It handles elaborated types, as well as enum types in the process.
3108void RewriteModernObjC::RewriteObjCFieldDecl(FieldDecl *fieldDecl,
3109 std::string &Result) {
3110 QualType Type = fieldDecl->getType();
3111 std::string Name = fieldDecl->getNameAsString();
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003112
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003113 bool EleboratedType = RewriteObjCFieldDeclType(Type, Result);
3114 if (!EleboratedType)
3115 Type.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003116 Result += Name;
3117 if (fieldDecl->isBitField()) {
3118 Result += " : "; Result += utostr(fieldDecl->getBitWidthValue(*Context));
3119 }
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003120 else if (EleboratedType && Type->isArrayType()) {
3121 CanQualType CType = Context->getCanonicalType(Type);
3122 while (isa<ArrayType>(CType)) {
3123 if (const ConstantArrayType *CAT = Context->getAsConstantArrayType(CType)) {
3124 Result += "[";
3125 llvm::APInt Dim = CAT->getSize();
3126 Result += utostr(Dim.getZExtValue());
3127 Result += "]";
3128 }
3129 CType = CType->getAs<ArrayType>()->getElementType();
3130 }
3131 }
3132
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003133 Result += ";\n";
3134}
3135
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003136/// RewriteObjCInternalStruct - Rewrite one internal struct corresponding to
3137/// an objective-c class with ivars.
3138void RewriteModernObjC::RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
3139 std::string &Result) {
3140 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
3141 assert(CDecl->getName() != "" &&
3142 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003143 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003144 SmallVector<ObjCIvarDecl *, 8> IVars;
3145 for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
Fariborz Jahanian9a2105b2012-03-06 17:16:27 +00003146 IVD; IVD = IVD->getNextIvar())
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003147 IVars.push_back(IVD);
Fariborz Jahanian9a2105b2012-03-06 17:16:27 +00003148
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003149 SourceLocation LocStart = CDecl->getLocStart();
3150 SourceLocation LocEnd = CDecl->getEndOfDefinitionLoc();
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003151
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003152 const char *startBuf = SM->getCharacterData(LocStart);
3153 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003154
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003155 // If no ivars and no root or if its root, directly or indirectly,
3156 // have no ivars (thus not synthesized) then no need to synthesize this class.
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003157 if ((!CDecl->isThisDeclarationADefinition() || IVars.size() == 0) &&
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003158 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
3159 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
3160 ReplaceText(LocStart, endBuf-startBuf, Result);
3161 return;
3162 }
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003163
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003164 Result += "\nstruct ";
3165 Result += CDecl->getNameAsString();
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003166 Result += "_IMPL {\n";
3167
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00003168 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003169 Result += "\tstruct "; Result += RCDecl->getNameAsString();
3170 Result += "_IMPL "; Result += RCDecl->getNameAsString();
3171 Result += "_IVARS;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003172 }
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003173 TagsDefinedInIvarDecls.clear();
3174 for (unsigned i = 0, e = IVars.size(); i < e; i++)
3175 RewriteObjCFieldDecl(IVars[i], Result);
Fariborz Jahanian0b17b9a2012-02-12 21:36:23 +00003176
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003177 Result += "};\n";
3178 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
3179 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00003180 // Mark this struct as having been generated.
3181 if (!ObjCSynthesizedStructs.insert(CDecl))
3182 llvm_unreachable("struct already synthesize- RewriteObjCInternalStruct");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003183}
3184
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00003185/// RewriteIvarOffsetSymbols - Rewrite ivar offset symbols of those ivars which
3186/// have been referenced in an ivar access expression.
3187void RewriteModernObjC::RewriteIvarOffsetSymbols(ObjCInterfaceDecl *CDecl,
3188 std::string &Result) {
3189 // write out ivar offset symbols which have been referenced in an ivar
3190 // access expression.
3191 llvm::SmallPtrSet<ObjCIvarDecl *, 8> Ivars = ReferencedIvars[CDecl];
3192 if (Ivars.empty())
3193 return;
3194 for (llvm::SmallPtrSet<ObjCIvarDecl *, 8>::iterator i = Ivars.begin(),
3195 e = Ivars.end(); i != e; i++) {
3196 ObjCIvarDecl *IvarDecl = (*i);
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00003197 Result += "\n";
3198 if (LangOpts.MicrosoftExt)
3199 Result += "__declspec(allocate(\".objc_ivar$B\")) ";
3200 if (LangOpts.MicrosoftExt &&
3201 IvarDecl->getAccessControl() != ObjCIvarDecl::Private &&
3202 IvarDecl->getAccessControl() != ObjCIvarDecl::Package) {
3203 const ObjCInterfaceDecl *CDecl = IvarDecl->getContainingInterface();
3204 if (CDecl->getImplementation())
3205 Result += "__declspec(dllexport) ";
3206 }
3207 Result += "extern unsigned long OBJC_IVAR_$_";
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00003208 Result += CDecl->getName(); Result += "_";
3209 Result += IvarDecl->getName(); Result += ";";
3210 }
3211}
3212
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003213//===----------------------------------------------------------------------===//
3214// Meta Data Emission
3215//===----------------------------------------------------------------------===//
3216
3217
3218/// RewriteImplementations - This routine rewrites all method implementations
3219/// and emits meta-data.
3220
3221void RewriteModernObjC::RewriteImplementations() {
3222 int ClsDefCount = ClassImplementation.size();
3223 int CatDefCount = CategoryImplementation.size();
3224
3225 // Rewrite implemented methods
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00003226 for (int i = 0; i < ClsDefCount; i++) {
3227 ObjCImplementationDecl *OIMP = ClassImplementation[i];
3228 ObjCInterfaceDecl *CDecl = OIMP->getClassInterface();
3229 if (CDecl->isImplicitInterfaceDecl())
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +00003230 assert(false &&
3231 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00003232 RewriteImplementationDecl(OIMP);
3233 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003234
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00003235 for (int i = 0; i < CatDefCount; i++) {
3236 ObjCCategoryImplDecl *CIMP = CategoryImplementation[i];
3237 ObjCInterfaceDecl *CDecl = CIMP->getClassInterface();
3238 if (CDecl->isImplicitInterfaceDecl())
3239 assert(false &&
3240 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00003241 RewriteImplementationDecl(CIMP);
3242 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003243}
3244
3245void RewriteModernObjC::RewriteByRefString(std::string &ResultStr,
3246 const std::string &Name,
3247 ValueDecl *VD, bool def) {
3248 assert(BlockByRefDeclNo.count(VD) &&
3249 "RewriteByRefString: ByRef decl missing");
3250 if (def)
3251 ResultStr += "struct ";
3252 ResultStr += "__Block_byref_" + Name +
3253 "_" + utostr(BlockByRefDeclNo[VD]) ;
3254}
3255
3256static bool HasLocalVariableExternalStorage(ValueDecl *VD) {
3257 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
3258 return (Var->isFunctionOrMethodVarDecl() && !Var->hasLocalStorage());
3259 return false;
3260}
3261
3262std::string RewriteModernObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
3263 StringRef funcName,
3264 std::string Tag) {
3265 const FunctionType *AFT = CE->getFunctionType();
3266 QualType RT = AFT->getResultType();
3267 std::string StructRef = "struct " + Tag;
3268 std::string S = "static " + RT.getAsString(Context->getPrintingPolicy()) + " __" +
3269 funcName.str() + "_" + "block_func_" + utostr(i);
3270
3271 BlockDecl *BD = CE->getBlockDecl();
3272
3273 if (isa<FunctionNoProtoType>(AFT)) {
3274 // No user-supplied arguments. Still need to pass in a pointer to the
3275 // block (to reference imported block decl refs).
3276 S += "(" + StructRef + " *__cself)";
3277 } else if (BD->param_empty()) {
3278 S += "(" + StructRef + " *__cself)";
3279 } else {
3280 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
3281 assert(FT && "SynthesizeBlockFunc: No function proto");
3282 S += '(';
3283 // first add the implicit argument.
3284 S += StructRef + " *__cself, ";
3285 std::string ParamStr;
3286 for (BlockDecl::param_iterator AI = BD->param_begin(),
3287 E = BD->param_end(); AI != E; ++AI) {
3288 if (AI != BD->param_begin()) S += ", ";
3289 ParamStr = (*AI)->getNameAsString();
3290 QualType QT = (*AI)->getType();
3291 if (convertBlockPointerToFunctionPointer(QT))
3292 QT.getAsStringInternal(ParamStr, Context->getPrintingPolicy());
3293 else
3294 QT.getAsStringInternal(ParamStr, Context->getPrintingPolicy());
3295 S += ParamStr;
3296 }
3297 if (FT->isVariadic()) {
3298 if (!BD->param_empty()) S += ", ";
3299 S += "...";
3300 }
3301 S += ')';
3302 }
3303 S += " {\n";
3304
3305 // Create local declarations to avoid rewriting all closure decl ref exprs.
3306 // First, emit a declaration for all "by ref" decls.
3307 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3308 E = BlockByRefDecls.end(); I != E; ++I) {
3309 S += " ";
3310 std::string Name = (*I)->getNameAsString();
3311 std::string TypeString;
3312 RewriteByRefString(TypeString, Name, (*I));
3313 TypeString += " *";
3314 Name = TypeString + Name;
3315 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
3316 }
3317 // Next, emit a declaration for all "by copy" declarations.
3318 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3319 E = BlockByCopyDecls.end(); I != E; ++I) {
3320 S += " ";
3321 // Handle nested closure invocation. For example:
3322 //
3323 // void (^myImportedClosure)(void);
3324 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
3325 //
3326 // void (^anotherClosure)(void);
3327 // anotherClosure = ^(void) {
3328 // myImportedClosure(); // import and invoke the closure
3329 // };
3330 //
3331 if (isTopLevelBlockPointerType((*I)->getType())) {
3332 RewriteBlockPointerTypeVariable(S, (*I));
3333 S += " = (";
3334 RewriteBlockPointerType(S, (*I)->getType());
3335 S += ")";
3336 S += "__cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
3337 }
3338 else {
3339 std::string Name = (*I)->getNameAsString();
3340 QualType QT = (*I)->getType();
3341 if (HasLocalVariableExternalStorage(*I))
3342 QT = Context->getPointerType(QT);
3343 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
3344 S += Name + " = __cself->" +
3345 (*I)->getNameAsString() + "; // bound by copy\n";
3346 }
3347 }
3348 std::string RewrittenStr = RewrittenBlockExprs[CE];
3349 const char *cstr = RewrittenStr.c_str();
3350 while (*cstr++ != '{') ;
3351 S += cstr;
3352 S += "\n";
3353 return S;
3354}
3355
3356std::string RewriteModernObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
3357 StringRef funcName,
3358 std::string Tag) {
3359 std::string StructRef = "struct " + Tag;
3360 std::string S = "static void __";
3361
3362 S += funcName;
3363 S += "_block_copy_" + utostr(i);
3364 S += "(" + StructRef;
3365 S += "*dst, " + StructRef;
3366 S += "*src) {";
3367 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
3368 E = ImportedBlockDecls.end(); I != E; ++I) {
3369 ValueDecl *VD = (*I);
3370 S += "_Block_object_assign((void*)&dst->";
3371 S += (*I)->getNameAsString();
3372 S += ", (void*)src->";
3373 S += (*I)->getNameAsString();
3374 if (BlockByRefDeclsPtrSet.count((*I)))
3375 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
3376 else if (VD->getType()->isBlockPointerType())
3377 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
3378 else
3379 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
3380 }
3381 S += "}\n";
3382
3383 S += "\nstatic void __";
3384 S += funcName;
3385 S += "_block_dispose_" + utostr(i);
3386 S += "(" + StructRef;
3387 S += "*src) {";
3388 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
3389 E = ImportedBlockDecls.end(); I != E; ++I) {
3390 ValueDecl *VD = (*I);
3391 S += "_Block_object_dispose((void*)src->";
3392 S += (*I)->getNameAsString();
3393 if (BlockByRefDeclsPtrSet.count((*I)))
3394 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
3395 else if (VD->getType()->isBlockPointerType())
3396 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
3397 else
3398 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
3399 }
3400 S += "}\n";
3401 return S;
3402}
3403
3404std::string RewriteModernObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
3405 std::string Desc) {
3406 std::string S = "\nstruct " + Tag;
3407 std::string Constructor = " " + Tag;
3408
3409 S += " {\n struct __block_impl impl;\n";
3410 S += " struct " + Desc;
3411 S += "* Desc;\n";
3412
3413 Constructor += "(void *fp, "; // Invoke function pointer.
3414 Constructor += "struct " + Desc; // Descriptor pointer.
3415 Constructor += " *desc";
3416
3417 if (BlockDeclRefs.size()) {
3418 // Output all "by copy" declarations.
3419 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3420 E = BlockByCopyDecls.end(); I != E; ++I) {
3421 S += " ";
3422 std::string FieldName = (*I)->getNameAsString();
3423 std::string ArgName = "_" + FieldName;
3424 // Handle nested closure invocation. For example:
3425 //
3426 // void (^myImportedBlock)(void);
3427 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
3428 //
3429 // void (^anotherBlock)(void);
3430 // anotherBlock = ^(void) {
3431 // myImportedBlock(); // import and invoke the closure
3432 // };
3433 //
3434 if (isTopLevelBlockPointerType((*I)->getType())) {
3435 S += "struct __block_impl *";
3436 Constructor += ", void *" + ArgName;
3437 } else {
3438 QualType QT = (*I)->getType();
3439 if (HasLocalVariableExternalStorage(*I))
3440 QT = Context->getPointerType(QT);
3441 QT.getAsStringInternal(FieldName, Context->getPrintingPolicy());
3442 QT.getAsStringInternal(ArgName, Context->getPrintingPolicy());
3443 Constructor += ", " + ArgName;
3444 }
3445 S += FieldName + ";\n";
3446 }
3447 // Output all "by ref" declarations.
3448 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3449 E = BlockByRefDecls.end(); I != E; ++I) {
3450 S += " ";
3451 std::string FieldName = (*I)->getNameAsString();
3452 std::string ArgName = "_" + FieldName;
3453 {
3454 std::string TypeString;
3455 RewriteByRefString(TypeString, FieldName, (*I));
3456 TypeString += " *";
3457 FieldName = TypeString + FieldName;
3458 ArgName = TypeString + ArgName;
3459 Constructor += ", " + ArgName;
3460 }
3461 S += FieldName + "; // by ref\n";
3462 }
3463 // Finish writing the constructor.
3464 Constructor += ", int flags=0)";
3465 // Initialize all "by copy" arguments.
3466 bool firsTime = true;
3467 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3468 E = BlockByCopyDecls.end(); I != E; ++I) {
3469 std::string Name = (*I)->getNameAsString();
3470 if (firsTime) {
3471 Constructor += " : ";
3472 firsTime = false;
3473 }
3474 else
3475 Constructor += ", ";
3476 if (isTopLevelBlockPointerType((*I)->getType()))
3477 Constructor += Name + "((struct __block_impl *)_" + Name + ")";
3478 else
3479 Constructor += Name + "(_" + Name + ")";
3480 }
3481 // Initialize all "by ref" arguments.
3482 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3483 E = BlockByRefDecls.end(); I != E; ++I) {
3484 std::string Name = (*I)->getNameAsString();
3485 if (firsTime) {
3486 Constructor += " : ";
3487 firsTime = false;
3488 }
3489 else
3490 Constructor += ", ";
3491 Constructor += Name + "(_" + Name + "->__forwarding)";
3492 }
3493
3494 Constructor += " {\n";
3495 if (GlobalVarDecl)
3496 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
3497 else
3498 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
3499 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3500
3501 Constructor += " Desc = desc;\n";
3502 } else {
3503 // Finish writing the constructor.
3504 Constructor += ", int flags=0) {\n";
3505 if (GlobalVarDecl)
3506 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
3507 else
3508 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
3509 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3510 Constructor += " Desc = desc;\n";
3511 }
3512 Constructor += " ";
3513 Constructor += "}\n";
3514 S += Constructor;
3515 S += "};\n";
3516 return S;
3517}
3518
3519std::string RewriteModernObjC::SynthesizeBlockDescriptor(std::string DescTag,
3520 std::string ImplTag, int i,
3521 StringRef FunName,
3522 unsigned hasCopy) {
3523 std::string S = "\nstatic struct " + DescTag;
3524
3525 S += " {\n unsigned long reserved;\n";
3526 S += " unsigned long Block_size;\n";
3527 if (hasCopy) {
3528 S += " void (*copy)(struct ";
3529 S += ImplTag; S += "*, struct ";
3530 S += ImplTag; S += "*);\n";
3531
3532 S += " void (*dispose)(struct ";
3533 S += ImplTag; S += "*);\n";
3534 }
3535 S += "} ";
3536
3537 S += DescTag + "_DATA = { 0, sizeof(struct ";
3538 S += ImplTag + ")";
3539 if (hasCopy) {
3540 S += ", __" + FunName.str() + "_block_copy_" + utostr(i);
3541 S += ", __" + FunName.str() + "_block_dispose_" + utostr(i);
3542 }
3543 S += "};\n";
3544 return S;
3545}
3546
3547void RewriteModernObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
3548 StringRef FunName) {
3549 // Insert declaration for the function in which block literal is used.
3550 if (CurFunctionDeclToDeclareForBlock && !Blocks.empty())
3551 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
3552 bool RewriteSC = (GlobalVarDecl &&
3553 !Blocks.empty() &&
3554 GlobalVarDecl->getStorageClass() == SC_Static &&
3555 GlobalVarDecl->getType().getCVRQualifiers());
3556 if (RewriteSC) {
3557 std::string SC(" void __");
3558 SC += GlobalVarDecl->getNameAsString();
3559 SC += "() {}";
3560 InsertText(FunLocStart, SC);
3561 }
3562
3563 // Insert closures that were part of the function.
3564 for (unsigned i = 0, count=0; i < Blocks.size(); i++) {
3565 CollectBlockDeclRefInfo(Blocks[i]);
3566 // Need to copy-in the inner copied-in variables not actually used in this
3567 // block.
3568 for (int j = 0; j < InnerDeclRefsCount[i]; j++) {
John McCallf4b88a42012-03-10 09:33:50 +00003569 DeclRefExpr *Exp = InnerDeclRefs[count++];
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003570 ValueDecl *VD = Exp->getDecl();
3571 BlockDeclRefs.push_back(Exp);
John McCallf4b88a42012-03-10 09:33:50 +00003572 if (!VD->hasAttr<BlocksAttr>()) {
3573 if (!BlockByCopyDeclsPtrSet.count(VD)) {
3574 BlockByCopyDeclsPtrSet.insert(VD);
3575 BlockByCopyDecls.push_back(VD);
3576 }
3577 continue;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003578 }
John McCallf4b88a42012-03-10 09:33:50 +00003579
3580 if (!BlockByRefDeclsPtrSet.count(VD)) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003581 BlockByRefDeclsPtrSet.insert(VD);
3582 BlockByRefDecls.push_back(VD);
3583 }
John McCallf4b88a42012-03-10 09:33:50 +00003584
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003585 // imported objects in the inner blocks not used in the outer
3586 // blocks must be copied/disposed in the outer block as well.
John McCallf4b88a42012-03-10 09:33:50 +00003587 if (VD->getType()->isObjCObjectPointerType() ||
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003588 VD->getType()->isBlockPointerType())
3589 ImportedBlockDecls.insert(VD);
3590 }
3591
3592 std::string ImplTag = "__" + FunName.str() + "_block_impl_" + utostr(i);
3593 std::string DescTag = "__" + FunName.str() + "_block_desc_" + utostr(i);
3594
3595 std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
3596
3597 InsertText(FunLocStart, CI);
3598
3599 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
3600
3601 InsertText(FunLocStart, CF);
3602
3603 if (ImportedBlockDecls.size()) {
3604 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
3605 InsertText(FunLocStart, HF);
3606 }
3607 std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
3608 ImportedBlockDecls.size() > 0);
3609 InsertText(FunLocStart, BD);
3610
3611 BlockDeclRefs.clear();
3612 BlockByRefDecls.clear();
3613 BlockByRefDeclsPtrSet.clear();
3614 BlockByCopyDecls.clear();
3615 BlockByCopyDeclsPtrSet.clear();
3616 ImportedBlockDecls.clear();
3617 }
3618 if (RewriteSC) {
3619 // Must insert any 'const/volatile/static here. Since it has been
3620 // removed as result of rewriting of block literals.
3621 std::string SC;
3622 if (GlobalVarDecl->getStorageClass() == SC_Static)
3623 SC = "static ";
3624 if (GlobalVarDecl->getType().isConstQualified())
3625 SC += "const ";
3626 if (GlobalVarDecl->getType().isVolatileQualified())
3627 SC += "volatile ";
3628 if (GlobalVarDecl->getType().isRestrictQualified())
3629 SC += "restrict ";
3630 InsertText(FunLocStart, SC);
3631 }
3632
3633 Blocks.clear();
3634 InnerDeclRefsCount.clear();
3635 InnerDeclRefs.clear();
3636 RewrittenBlockExprs.clear();
3637}
3638
3639void RewriteModernObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
3640 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
3641 StringRef FuncName = FD->getName();
3642
3643 SynthesizeBlockLiterals(FunLocStart, FuncName);
3644}
3645
3646static void BuildUniqueMethodName(std::string &Name,
3647 ObjCMethodDecl *MD) {
3648 ObjCInterfaceDecl *IFace = MD->getClassInterface();
3649 Name = IFace->getName();
3650 Name += "__" + MD->getSelector().getAsString();
3651 // Convert colons to underscores.
3652 std::string::size_type loc = 0;
3653 while ((loc = Name.find(":", loc)) != std::string::npos)
3654 Name.replace(loc, 1, "_");
3655}
3656
3657void RewriteModernObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
3658 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
3659 //SourceLocation FunLocStart = MD->getLocStart();
3660 SourceLocation FunLocStart = MD->getLocStart();
3661 std::string FuncName;
3662 BuildUniqueMethodName(FuncName, MD);
3663 SynthesizeBlockLiterals(FunLocStart, FuncName);
3664}
3665
3666void RewriteModernObjC::GetBlockDeclRefExprs(Stmt *S) {
3667 for (Stmt::child_range CI = S->children(); CI; ++CI)
3668 if (*CI) {
3669 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
3670 GetBlockDeclRefExprs(CBE->getBody());
3671 else
3672 GetBlockDeclRefExprs(*CI);
3673 }
3674 // Handle specific things.
John McCallf4b88a42012-03-10 09:33:50 +00003675 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S))
3676 if (DRE->refersToEnclosingLocal() &&
3677 HasLocalVariableExternalStorage(DRE->getDecl())) {
3678 BlockDeclRefs.push_back(DRE);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003679 }
3680
3681 return;
3682}
3683
3684void RewriteModernObjC::GetInnerBlockDeclRefExprs(Stmt *S,
John McCallf4b88a42012-03-10 09:33:50 +00003685 SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003686 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts) {
3687 for (Stmt::child_range CI = S->children(); CI; ++CI)
3688 if (*CI) {
3689 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI)) {
3690 InnerContexts.insert(cast<DeclContext>(CBE->getBlockDecl()));
3691 GetInnerBlockDeclRefExprs(CBE->getBody(),
3692 InnerBlockDeclRefs,
3693 InnerContexts);
3694 }
3695 else
3696 GetInnerBlockDeclRefExprs(*CI,
3697 InnerBlockDeclRefs,
3698 InnerContexts);
3699
3700 }
3701 // Handle specific things.
John McCallf4b88a42012-03-10 09:33:50 +00003702 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
3703 if (DRE->refersToEnclosingLocal()) {
3704 if (!isa<FunctionDecl>(DRE->getDecl()) &&
3705 !InnerContexts.count(DRE->getDecl()->getDeclContext()))
3706 InnerBlockDeclRefs.push_back(DRE);
3707 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl()))
3708 if (Var->isFunctionOrMethodVarDecl())
3709 ImportedLocalExternalDecls.insert(Var);
3710 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003711 }
3712
3713 return;
3714}
3715
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00003716/// convertObjCTypeToCStyleType - This routine converts such objc types
3717/// as qualified objects, and blocks to their closest c/c++ types that
3718/// it can. It returns true if input type was modified.
3719bool RewriteModernObjC::convertObjCTypeToCStyleType(QualType &T) {
3720 QualType oldT = T;
3721 convertBlockPointerToFunctionPointer(T);
3722 if (T->isFunctionPointerType()) {
3723 QualType PointeeTy;
3724 if (const PointerType* PT = T->getAs<PointerType>()) {
3725 PointeeTy = PT->getPointeeType();
3726 if (const FunctionType *FT = PointeeTy->getAs<FunctionType>()) {
3727 T = convertFunctionTypeOfBlocks(FT);
3728 T = Context->getPointerType(T);
3729 }
3730 }
3731 }
3732
3733 convertToUnqualifiedObjCType(T);
3734 return T != oldT;
3735}
3736
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003737/// convertFunctionTypeOfBlocks - This routine converts a function type
3738/// whose result type may be a block pointer or whose argument type(s)
3739/// might be block pointers to an equivalent function type replacing
3740/// all block pointers to function pointers.
3741QualType RewriteModernObjC::convertFunctionTypeOfBlocks(const FunctionType *FT) {
3742 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
3743 // FTP will be null for closures that don't take arguments.
3744 // Generate a funky cast.
3745 SmallVector<QualType, 8> ArgTypes;
3746 QualType Res = FT->getResultType();
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00003747 bool modified = convertObjCTypeToCStyleType(Res);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003748
3749 if (FTP) {
3750 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
3751 E = FTP->arg_type_end(); I && (I != E); ++I) {
3752 QualType t = *I;
3753 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00003754 if (convertObjCTypeToCStyleType(t))
3755 modified = true;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003756 ArgTypes.push_back(t);
3757 }
3758 }
3759 QualType FuncType;
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00003760 if (modified)
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003761 FuncType = getSimpleFunctionType(Res, &ArgTypes[0], ArgTypes.size());
3762 else FuncType = QualType(FT, 0);
3763 return FuncType;
3764}
3765
3766Stmt *RewriteModernObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
3767 // Navigate to relevant type information.
3768 const BlockPointerType *CPT = 0;
3769
3770 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
3771 CPT = DRE->getType()->getAs<BlockPointerType>();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003772 } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
3773 CPT = MExpr->getType()->getAs<BlockPointerType>();
3774 }
3775 else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
3776 return SynthesizeBlockCall(Exp, PRE->getSubExpr());
3777 }
3778 else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
3779 CPT = IEXPR->getType()->getAs<BlockPointerType>();
3780 else if (const ConditionalOperator *CEXPR =
3781 dyn_cast<ConditionalOperator>(BlockExp)) {
3782 Expr *LHSExp = CEXPR->getLHS();
3783 Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
3784 Expr *RHSExp = CEXPR->getRHS();
3785 Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
3786 Expr *CONDExp = CEXPR->getCond();
3787 ConditionalOperator *CondExpr =
3788 new (Context) ConditionalOperator(CONDExp,
3789 SourceLocation(), cast<Expr>(LHSStmt),
3790 SourceLocation(), cast<Expr>(RHSStmt),
3791 Exp->getType(), VK_RValue, OK_Ordinary);
3792 return CondExpr;
3793 } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
3794 CPT = IRE->getType()->getAs<BlockPointerType>();
3795 } else if (const PseudoObjectExpr *POE
3796 = dyn_cast<PseudoObjectExpr>(BlockExp)) {
3797 CPT = POE->getType()->castAs<BlockPointerType>();
3798 } else {
3799 assert(1 && "RewriteBlockClass: Bad type");
3800 }
3801 assert(CPT && "RewriteBlockClass: Bad type");
3802 const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
3803 assert(FT && "RewriteBlockClass: Bad type");
3804 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
3805 // FTP will be null for closures that don't take arguments.
3806
3807 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
3808 SourceLocation(), SourceLocation(),
3809 &Context->Idents.get("__block_impl"));
3810 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
3811
3812 // Generate a funky cast.
3813 SmallVector<QualType, 8> ArgTypes;
3814
3815 // Push the block argument type.
3816 ArgTypes.push_back(PtrBlock);
3817 if (FTP) {
3818 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
3819 E = FTP->arg_type_end(); I && (I != E); ++I) {
3820 QualType t = *I;
3821 // Make sure we convert "t (^)(...)" to "t (*)(...)".
3822 if (!convertBlockPointerToFunctionPointer(t))
3823 convertToUnqualifiedObjCType(t);
3824 ArgTypes.push_back(t);
3825 }
3826 }
3827 // Now do the pointer to function cast.
3828 QualType PtrToFuncCastType
3829 = getSimpleFunctionType(Exp->getType(), &ArgTypes[0], ArgTypes.size());
3830
3831 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
3832
3833 CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
3834 CK_BitCast,
3835 const_cast<Expr*>(BlockExp));
3836 // Don't forget the parens to enforce the proper binding.
3837 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3838 BlkCast);
3839 //PE->dump();
3840
3841 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
3842 SourceLocation(),
3843 &Context->Idents.get("FuncPtr"),
3844 Context->VoidPtrTy, 0,
3845 /*BitWidth=*/0, /*Mutable=*/true,
3846 /*HasInit=*/false);
3847 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
3848 FD->getType(), VK_LValue,
3849 OK_Ordinary);
3850
3851
3852 CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
3853 CK_BitCast, ME);
3854 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
3855
3856 SmallVector<Expr*, 8> BlkExprs;
3857 // Add the implicit argument.
3858 BlkExprs.push_back(BlkCast);
3859 // Add the user arguments.
3860 for (CallExpr::arg_iterator I = Exp->arg_begin(),
3861 E = Exp->arg_end(); I != E; ++I) {
3862 BlkExprs.push_back(*I);
3863 }
3864 CallExpr *CE = new (Context) CallExpr(*Context, PE, &BlkExprs[0],
3865 BlkExprs.size(),
3866 Exp->getType(), VK_RValue,
3867 SourceLocation());
3868 return CE;
3869}
3870
3871// We need to return the rewritten expression to handle cases where the
John McCallf4b88a42012-03-10 09:33:50 +00003872// DeclRefExpr is embedded in another expression being rewritten.
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003873// For example:
3874//
3875// int main() {
3876// __block Foo *f;
3877// __block int i;
3878//
3879// void (^myblock)() = ^() {
John McCallf4b88a42012-03-10 09:33:50 +00003880// [f test]; // f is a DeclRefExpr embedded in a message (which is being rewritten).
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003881// i = 77;
3882// };
3883//}
John McCallf4b88a42012-03-10 09:33:50 +00003884Stmt *RewriteModernObjC::RewriteBlockDeclRefExpr(DeclRefExpr *DeclRefExp) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003885 // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
3886 // for each DeclRefExp where BYREFVAR is name of the variable.
John McCallf4b88a42012-03-10 09:33:50 +00003887 ValueDecl *VD = DeclRefExp->getDecl();
3888 bool isArrow = DeclRefExp->refersToEnclosingLocal();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003889
3890 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
3891 SourceLocation(),
3892 &Context->Idents.get("__forwarding"),
3893 Context->VoidPtrTy, 0,
3894 /*BitWidth=*/0, /*Mutable=*/true,
3895 /*HasInit=*/false);
3896 MemberExpr *ME = new (Context) MemberExpr(DeclRefExp, isArrow,
3897 FD, SourceLocation(),
3898 FD->getType(), VK_LValue,
3899 OK_Ordinary);
3900
3901 StringRef Name = VD->getName();
3902 FD = FieldDecl::Create(*Context, 0, SourceLocation(), SourceLocation(),
3903 &Context->Idents.get(Name),
3904 Context->VoidPtrTy, 0,
3905 /*BitWidth=*/0, /*Mutable=*/true,
3906 /*HasInit=*/false);
3907 ME = new (Context) MemberExpr(ME, true, FD, SourceLocation(),
3908 DeclRefExp->getType(), VK_LValue, OK_Ordinary);
3909
3910
3911
3912 // Need parens to enforce precedence.
3913 ParenExpr *PE = new (Context) ParenExpr(DeclRefExp->getExprLoc(),
3914 DeclRefExp->getExprLoc(),
3915 ME);
3916 ReplaceStmt(DeclRefExp, PE);
3917 return PE;
3918}
3919
3920// Rewrites the imported local variable V with external storage
3921// (static, extern, etc.) as *V
3922//
3923Stmt *RewriteModernObjC::RewriteLocalVariableExternalStorage(DeclRefExpr *DRE) {
3924 ValueDecl *VD = DRE->getDecl();
3925 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
3926 if (!ImportedLocalExternalDecls.count(Var))
3927 return DRE;
3928 Expr *Exp = new (Context) UnaryOperator(DRE, UO_Deref, DRE->getType(),
3929 VK_LValue, OK_Ordinary,
3930 DRE->getLocation());
3931 // Need parens to enforce precedence.
3932 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3933 Exp);
3934 ReplaceStmt(DRE, PE);
3935 return PE;
3936}
3937
3938void RewriteModernObjC::RewriteCastExpr(CStyleCastExpr *CE) {
3939 SourceLocation LocStart = CE->getLParenLoc();
3940 SourceLocation LocEnd = CE->getRParenLoc();
3941
3942 // Need to avoid trying to rewrite synthesized casts.
3943 if (LocStart.isInvalid())
3944 return;
3945 // Need to avoid trying to rewrite casts contained in macros.
3946 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
3947 return;
3948
3949 const char *startBuf = SM->getCharacterData(LocStart);
3950 const char *endBuf = SM->getCharacterData(LocEnd);
3951 QualType QT = CE->getType();
3952 const Type* TypePtr = QT->getAs<Type>();
3953 if (isa<TypeOfExprType>(TypePtr)) {
3954 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
3955 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
3956 std::string TypeAsString = "(";
3957 RewriteBlockPointerType(TypeAsString, QT);
3958 TypeAsString += ")";
3959 ReplaceText(LocStart, endBuf-startBuf+1, TypeAsString);
3960 return;
3961 }
3962 // advance the location to startArgList.
3963 const char *argPtr = startBuf;
3964
3965 while (*argPtr++ && (argPtr < endBuf)) {
3966 switch (*argPtr) {
3967 case '^':
3968 // Replace the '^' with '*'.
3969 LocStart = LocStart.getLocWithOffset(argPtr-startBuf);
3970 ReplaceText(LocStart, 1, "*");
3971 break;
3972 }
3973 }
3974 return;
3975}
3976
3977void RewriteModernObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
3978 SourceLocation DeclLoc = FD->getLocation();
3979 unsigned parenCount = 0;
3980
3981 // We have 1 or more arguments that have closure pointers.
3982 const char *startBuf = SM->getCharacterData(DeclLoc);
3983 const char *startArgList = strchr(startBuf, '(');
3984
3985 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
3986
3987 parenCount++;
3988 // advance the location to startArgList.
3989 DeclLoc = DeclLoc.getLocWithOffset(startArgList-startBuf);
3990 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
3991
3992 const char *argPtr = startArgList;
3993
3994 while (*argPtr++ && parenCount) {
3995 switch (*argPtr) {
3996 case '^':
3997 // Replace the '^' with '*'.
3998 DeclLoc = DeclLoc.getLocWithOffset(argPtr-startArgList);
3999 ReplaceText(DeclLoc, 1, "*");
4000 break;
4001 case '(':
4002 parenCount++;
4003 break;
4004 case ')':
4005 parenCount--;
4006 break;
4007 }
4008 }
4009 return;
4010}
4011
4012bool RewriteModernObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
4013 const FunctionProtoType *FTP;
4014 const PointerType *PT = QT->getAs<PointerType>();
4015 if (PT) {
4016 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4017 } else {
4018 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4019 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4020 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4021 }
4022 if (FTP) {
4023 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4024 E = FTP->arg_type_end(); I != E; ++I)
4025 if (isTopLevelBlockPointerType(*I))
4026 return true;
4027 }
4028 return false;
4029}
4030
4031bool RewriteModernObjC::PointerTypeTakesAnyObjCQualifiedType(QualType QT) {
4032 const FunctionProtoType *FTP;
4033 const PointerType *PT = QT->getAs<PointerType>();
4034 if (PT) {
4035 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4036 } else {
4037 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4038 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4039 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4040 }
4041 if (FTP) {
4042 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4043 E = FTP->arg_type_end(); I != E; ++I) {
4044 if ((*I)->isObjCQualifiedIdType())
4045 return true;
4046 if ((*I)->isObjCObjectPointerType() &&
4047 (*I)->getPointeeType()->isObjCQualifiedInterfaceType())
4048 return true;
4049 }
4050
4051 }
4052 return false;
4053}
4054
4055void RewriteModernObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
4056 const char *&RParen) {
4057 const char *argPtr = strchr(Name, '(');
4058 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
4059
4060 LParen = argPtr; // output the start.
4061 argPtr++; // skip past the left paren.
4062 unsigned parenCount = 1;
4063
4064 while (*argPtr && parenCount) {
4065 switch (*argPtr) {
4066 case '(': parenCount++; break;
4067 case ')': parenCount--; break;
4068 default: break;
4069 }
4070 if (parenCount) argPtr++;
4071 }
4072 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
4073 RParen = argPtr; // output the end
4074}
4075
4076void RewriteModernObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
4077 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4078 RewriteBlockPointerFunctionArgs(FD);
4079 return;
4080 }
4081 // Handle Variables and Typedefs.
4082 SourceLocation DeclLoc = ND->getLocation();
4083 QualType DeclT;
4084 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
4085 DeclT = VD->getType();
4086 else if (TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(ND))
4087 DeclT = TDD->getUnderlyingType();
4088 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
4089 DeclT = FD->getType();
4090 else
4091 llvm_unreachable("RewriteBlockPointerDecl(): Decl type not yet handled");
4092
4093 const char *startBuf = SM->getCharacterData(DeclLoc);
4094 const char *endBuf = startBuf;
4095 // scan backward (from the decl location) for the end of the previous decl.
4096 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
4097 startBuf--;
4098 SourceLocation Start = DeclLoc.getLocWithOffset(startBuf-endBuf);
4099 std::string buf;
4100 unsigned OrigLength=0;
4101 // *startBuf != '^' if we are dealing with a pointer to function that
4102 // may take block argument types (which will be handled below).
4103 if (*startBuf == '^') {
4104 // Replace the '^' with '*', computing a negative offset.
4105 buf = '*';
4106 startBuf++;
4107 OrigLength++;
4108 }
4109 while (*startBuf != ')') {
4110 buf += *startBuf;
4111 startBuf++;
4112 OrigLength++;
4113 }
4114 buf += ')';
4115 OrigLength++;
4116
4117 if (PointerTypeTakesAnyBlockArguments(DeclT) ||
4118 PointerTypeTakesAnyObjCQualifiedType(DeclT)) {
4119 // Replace the '^' with '*' for arguments.
4120 // Replace id<P> with id/*<>*/
4121 DeclLoc = ND->getLocation();
4122 startBuf = SM->getCharacterData(DeclLoc);
4123 const char *argListBegin, *argListEnd;
4124 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
4125 while (argListBegin < argListEnd) {
4126 if (*argListBegin == '^')
4127 buf += '*';
4128 else if (*argListBegin == '<') {
4129 buf += "/*";
4130 buf += *argListBegin++;
4131 OrigLength++;;
4132 while (*argListBegin != '>') {
4133 buf += *argListBegin++;
4134 OrigLength++;
4135 }
4136 buf += *argListBegin;
4137 buf += "*/";
4138 }
4139 else
4140 buf += *argListBegin;
4141 argListBegin++;
4142 OrigLength++;
4143 }
4144 buf += ')';
4145 OrigLength++;
4146 }
4147 ReplaceText(Start, OrigLength, buf);
4148
4149 return;
4150}
4151
4152
4153/// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
4154/// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
4155/// struct Block_byref_id_object *src) {
4156/// _Block_object_assign (&_dest->object, _src->object,
4157/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4158/// [|BLOCK_FIELD_IS_WEAK]) // object
4159/// _Block_object_assign(&_dest->object, _src->object,
4160/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4161/// [|BLOCK_FIELD_IS_WEAK]) // block
4162/// }
4163/// And:
4164/// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
4165/// _Block_object_dispose(_src->object,
4166/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4167/// [|BLOCK_FIELD_IS_WEAK]) // object
4168/// _Block_object_dispose(_src->object,
4169/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4170/// [|BLOCK_FIELD_IS_WEAK]) // block
4171/// }
4172
4173std::string RewriteModernObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
4174 int flag) {
4175 std::string S;
4176 if (CopyDestroyCache.count(flag))
4177 return S;
4178 CopyDestroyCache.insert(flag);
4179 S = "static void __Block_byref_id_object_copy_";
4180 S += utostr(flag);
4181 S += "(void *dst, void *src) {\n";
4182
4183 // offset into the object pointer is computed as:
4184 // void * + void* + int + int + void* + void *
4185 unsigned IntSize =
4186 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
4187 unsigned VoidPtrSize =
4188 static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
4189
4190 unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/Context->getCharWidth();
4191 S += " _Block_object_assign((char*)dst + ";
4192 S += utostr(offset);
4193 S += ", *(void * *) ((char*)src + ";
4194 S += utostr(offset);
4195 S += "), ";
4196 S += utostr(flag);
4197 S += ");\n}\n";
4198
4199 S += "static void __Block_byref_id_object_dispose_";
4200 S += utostr(flag);
4201 S += "(void *src) {\n";
4202 S += " _Block_object_dispose(*(void * *) ((char*)src + ";
4203 S += utostr(offset);
4204 S += "), ";
4205 S += utostr(flag);
4206 S += ");\n}\n";
4207 return S;
4208}
4209
4210/// RewriteByRefVar - For each __block typex ND variable this routine transforms
4211/// the declaration into:
4212/// struct __Block_byref_ND {
4213/// void *__isa; // NULL for everything except __weak pointers
4214/// struct __Block_byref_ND *__forwarding;
4215/// int32_t __flags;
4216/// int32_t __size;
4217/// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
4218/// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
4219/// typex ND;
4220/// };
4221///
4222/// It then replaces declaration of ND variable with:
4223/// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
4224/// __size=sizeof(struct __Block_byref_ND),
4225/// ND=initializer-if-any};
4226///
4227///
4228void RewriteModernObjC::RewriteByRefVar(VarDecl *ND) {
4229 // Insert declaration for the function in which block literal is
4230 // used.
4231 if (CurFunctionDeclToDeclareForBlock)
4232 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
4233 int flag = 0;
4234 int isa = 0;
4235 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
4236 if (DeclLoc.isInvalid())
4237 // If type location is missing, it is because of missing type (a warning).
4238 // Use variable's location which is good for this case.
4239 DeclLoc = ND->getLocation();
4240 const char *startBuf = SM->getCharacterData(DeclLoc);
4241 SourceLocation X = ND->getLocEnd();
4242 X = SM->getExpansionLoc(X);
4243 const char *endBuf = SM->getCharacterData(X);
4244 std::string Name(ND->getNameAsString());
4245 std::string ByrefType;
4246 RewriteByRefString(ByrefType, Name, ND, true);
4247 ByrefType += " {\n";
4248 ByrefType += " void *__isa;\n";
4249 RewriteByRefString(ByrefType, Name, ND);
4250 ByrefType += " *__forwarding;\n";
4251 ByrefType += " int __flags;\n";
4252 ByrefType += " int __size;\n";
4253 // Add void *__Block_byref_id_object_copy;
4254 // void *__Block_byref_id_object_dispose; if needed.
4255 QualType Ty = ND->getType();
4256 bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty);
4257 if (HasCopyAndDispose) {
4258 ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
4259 ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
4260 }
4261
4262 QualType T = Ty;
4263 (void)convertBlockPointerToFunctionPointer(T);
4264 T.getAsStringInternal(Name, Context->getPrintingPolicy());
4265
4266 ByrefType += " " + Name + ";\n";
4267 ByrefType += "};\n";
4268 // Insert this type in global scope. It is needed by helper function.
4269 SourceLocation FunLocStart;
4270 if (CurFunctionDef)
4271 FunLocStart = CurFunctionDef->getTypeSpecStartLoc();
4272 else {
4273 assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null");
4274 FunLocStart = CurMethodDef->getLocStart();
4275 }
4276 InsertText(FunLocStart, ByrefType);
4277 if (Ty.isObjCGCWeak()) {
4278 flag |= BLOCK_FIELD_IS_WEAK;
4279 isa = 1;
4280 }
4281
4282 if (HasCopyAndDispose) {
4283 flag = BLOCK_BYREF_CALLER;
4284 QualType Ty = ND->getType();
4285 // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
4286 if (Ty->isBlockPointerType())
4287 flag |= BLOCK_FIELD_IS_BLOCK;
4288 else
4289 flag |= BLOCK_FIELD_IS_OBJECT;
4290 std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
4291 if (!HF.empty())
4292 InsertText(FunLocStart, HF);
4293 }
4294
4295 // struct __Block_byref_ND ND =
4296 // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
4297 // initializer-if-any};
4298 bool hasInit = (ND->getInit() != 0);
4299 unsigned flags = 0;
4300 if (HasCopyAndDispose)
4301 flags |= BLOCK_HAS_COPY_DISPOSE;
4302 Name = ND->getNameAsString();
4303 ByrefType.clear();
4304 RewriteByRefString(ByrefType, Name, ND);
4305 std::string ForwardingCastType("(");
4306 ForwardingCastType += ByrefType + " *)";
4307 if (!hasInit) {
4308 ByrefType += " " + Name + " = {(void*)";
4309 ByrefType += utostr(isa);
4310 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
4311 ByrefType += utostr(flags);
4312 ByrefType += ", ";
4313 ByrefType += "sizeof(";
4314 RewriteByRefString(ByrefType, Name, ND);
4315 ByrefType += ")";
4316 if (HasCopyAndDispose) {
4317 ByrefType += ", __Block_byref_id_object_copy_";
4318 ByrefType += utostr(flag);
4319 ByrefType += ", __Block_byref_id_object_dispose_";
4320 ByrefType += utostr(flag);
4321 }
4322 ByrefType += "};\n";
4323 unsigned nameSize = Name.size();
4324 // for block or function pointer declaration. Name is aleady
4325 // part of the declaration.
4326 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType())
4327 nameSize = 1;
4328 ReplaceText(DeclLoc, endBuf-startBuf+nameSize, ByrefType);
4329 }
4330 else {
4331 SourceLocation startLoc;
4332 Expr *E = ND->getInit();
4333 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
4334 startLoc = ECE->getLParenLoc();
4335 else
4336 startLoc = E->getLocStart();
4337 startLoc = SM->getExpansionLoc(startLoc);
4338 endBuf = SM->getCharacterData(startLoc);
4339 ByrefType += " " + Name;
4340 ByrefType += " = {(void*)";
4341 ByrefType += utostr(isa);
4342 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
4343 ByrefType += utostr(flags);
4344 ByrefType += ", ";
4345 ByrefType += "sizeof(";
4346 RewriteByRefString(ByrefType, Name, ND);
4347 ByrefType += "), ";
4348 if (HasCopyAndDispose) {
4349 ByrefType += "__Block_byref_id_object_copy_";
4350 ByrefType += utostr(flag);
4351 ByrefType += ", __Block_byref_id_object_dispose_";
4352 ByrefType += utostr(flag);
4353 ByrefType += ", ";
4354 }
4355 ReplaceText(DeclLoc, endBuf-startBuf, ByrefType);
4356
4357 // Complete the newly synthesized compound expression by inserting a right
4358 // curly brace before the end of the declaration.
4359 // FIXME: This approach avoids rewriting the initializer expression. It
4360 // also assumes there is only one declarator. For example, the following
4361 // isn't currently supported by this routine (in general):
4362 //
4363 // double __block BYREFVAR = 1.34, BYREFVAR2 = 1.37;
4364 //
4365 const char *startInitializerBuf = SM->getCharacterData(startLoc);
4366 const char *semiBuf = strchr(startInitializerBuf, ';');
4367 assert((*semiBuf == ';') && "RewriteByRefVar: can't find ';'");
4368 SourceLocation semiLoc =
4369 startLoc.getLocWithOffset(semiBuf-startInitializerBuf);
4370
4371 InsertText(semiLoc, "}");
4372 }
4373 return;
4374}
4375
4376void RewriteModernObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
4377 // Add initializers for any closure decl refs.
4378 GetBlockDeclRefExprs(Exp->getBody());
4379 if (BlockDeclRefs.size()) {
4380 // Unique all "by copy" declarations.
4381 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00004382 if (!BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004383 if (!BlockByCopyDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
4384 BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
4385 BlockByCopyDecls.push_back(BlockDeclRefs[i]->getDecl());
4386 }
4387 }
4388 // Unique all "by ref" declarations.
4389 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00004390 if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004391 if (!BlockByRefDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
4392 BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
4393 BlockByRefDecls.push_back(BlockDeclRefs[i]->getDecl());
4394 }
4395 }
4396 // Find any imported blocks...they will need special attention.
4397 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00004398 if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004399 BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
4400 BlockDeclRefs[i]->getType()->isBlockPointerType())
4401 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
4402 }
4403}
4404
4405FunctionDecl *RewriteModernObjC::SynthBlockInitFunctionDecl(StringRef name) {
4406 IdentifierInfo *ID = &Context->Idents.get(name);
4407 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
4408 return FunctionDecl::Create(*Context, TUDecl, SourceLocation(),
4409 SourceLocation(), ID, FType, 0, SC_Extern,
4410 SC_None, false, false);
4411}
4412
4413Stmt *RewriteModernObjC::SynthBlockInitExpr(BlockExpr *Exp,
John McCallf4b88a42012-03-10 09:33:50 +00004414 const SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004415 const BlockDecl *block = Exp->getBlockDecl();
4416 Blocks.push_back(Exp);
4417
4418 CollectBlockDeclRefInfo(Exp);
4419
4420 // Add inner imported variables now used in current block.
4421 int countOfInnerDecls = 0;
4422 if (!InnerBlockDeclRefs.empty()) {
4423 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++) {
John McCallf4b88a42012-03-10 09:33:50 +00004424 DeclRefExpr *Exp = InnerBlockDeclRefs[i];
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004425 ValueDecl *VD = Exp->getDecl();
John McCallf4b88a42012-03-10 09:33:50 +00004426 if (!VD->hasAttr<BlocksAttr>() && !BlockByCopyDeclsPtrSet.count(VD)) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004427 // We need to save the copied-in variables in nested
4428 // blocks because it is needed at the end for some of the API generations.
4429 // See SynthesizeBlockLiterals routine.
4430 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
4431 BlockDeclRefs.push_back(Exp);
4432 BlockByCopyDeclsPtrSet.insert(VD);
4433 BlockByCopyDecls.push_back(VD);
4434 }
John McCallf4b88a42012-03-10 09:33:50 +00004435 if (VD->hasAttr<BlocksAttr>() && !BlockByRefDeclsPtrSet.count(VD)) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004436 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
4437 BlockDeclRefs.push_back(Exp);
4438 BlockByRefDeclsPtrSet.insert(VD);
4439 BlockByRefDecls.push_back(VD);
4440 }
4441 }
4442 // Find any imported blocks...they will need special attention.
4443 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00004444 if (InnerBlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004445 InnerBlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
4446 InnerBlockDeclRefs[i]->getType()->isBlockPointerType())
4447 ImportedBlockDecls.insert(InnerBlockDeclRefs[i]->getDecl());
4448 }
4449 InnerDeclRefsCount.push_back(countOfInnerDecls);
4450
4451 std::string FuncName;
4452
4453 if (CurFunctionDef)
4454 FuncName = CurFunctionDef->getNameAsString();
4455 else if (CurMethodDef)
4456 BuildUniqueMethodName(FuncName, CurMethodDef);
4457 else if (GlobalVarDecl)
4458 FuncName = std::string(GlobalVarDecl->getNameAsString());
4459
4460 std::string BlockNumber = utostr(Blocks.size()-1);
4461
4462 std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber;
4463 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
4464
4465 // Get a pointer to the function type so we can cast appropriately.
4466 QualType BFT = convertFunctionTypeOfBlocks(Exp->getFunctionType());
4467 QualType FType = Context->getPointerType(BFT);
4468
4469 FunctionDecl *FD;
4470 Expr *NewRep;
4471
4472 // Simulate a contructor call...
4473 FD = SynthBlockInitFunctionDecl(Tag);
John McCallf4b88a42012-03-10 09:33:50 +00004474 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, false, FType, VK_RValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004475 SourceLocation());
4476
4477 SmallVector<Expr*, 4> InitExprs;
4478
4479 // Initialize the block function.
4480 FD = SynthBlockInitFunctionDecl(Func);
John McCallf4b88a42012-03-10 09:33:50 +00004481 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, false, FD->getType(),
4482 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004483 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
4484 CK_BitCast, Arg);
4485 InitExprs.push_back(castExpr);
4486
4487 // Initialize the block descriptor.
4488 std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
4489
4490 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl,
4491 SourceLocation(), SourceLocation(),
4492 &Context->Idents.get(DescData.c_str()),
4493 Context->VoidPtrTy, 0,
4494 SC_Static, SC_None);
4495 UnaryOperator *DescRefExpr =
John McCallf4b88a42012-03-10 09:33:50 +00004496 new (Context) UnaryOperator(new (Context) DeclRefExpr(NewVD, false,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004497 Context->VoidPtrTy,
4498 VK_LValue,
4499 SourceLocation()),
4500 UO_AddrOf,
4501 Context->getPointerType(Context->VoidPtrTy),
4502 VK_RValue, OK_Ordinary,
4503 SourceLocation());
4504 InitExprs.push_back(DescRefExpr);
4505
4506 // Add initializers for any closure decl refs.
4507 if (BlockDeclRefs.size()) {
4508 Expr *Exp;
4509 // Output all "by copy" declarations.
4510 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
4511 E = BlockByCopyDecls.end(); I != E; ++I) {
4512 if (isObjCType((*I)->getType())) {
4513 // FIXME: Conform to ABI ([[obj retain] autorelease]).
4514 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00004515 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(),
4516 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004517 if (HasLocalVariableExternalStorage(*I)) {
4518 QualType QT = (*I)->getType();
4519 QT = Context->getPointerType(QT);
4520 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
4521 OK_Ordinary, SourceLocation());
4522 }
4523 } else if (isTopLevelBlockPointerType((*I)->getType())) {
4524 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00004525 Arg = new (Context) DeclRefExpr(FD, false, FD->getType(),
4526 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004527 Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
4528 CK_BitCast, Arg);
4529 } else {
4530 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00004531 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(),
4532 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004533 if (HasLocalVariableExternalStorage(*I)) {
4534 QualType QT = (*I)->getType();
4535 QT = Context->getPointerType(QT);
4536 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
4537 OK_Ordinary, SourceLocation());
4538 }
4539
4540 }
4541 InitExprs.push_back(Exp);
4542 }
4543 // Output all "by ref" declarations.
4544 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
4545 E = BlockByRefDecls.end(); I != E; ++I) {
4546 ValueDecl *ND = (*I);
4547 std::string Name(ND->getNameAsString());
4548 std::string RecName;
4549 RewriteByRefString(RecName, Name, ND, true);
4550 IdentifierInfo *II = &Context->Idents.get(RecName.c_str()
4551 + sizeof("struct"));
4552 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
4553 SourceLocation(), SourceLocation(),
4554 II);
4555 assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl");
4556 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
4557
4558 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00004559 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(), VK_LValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004560 SourceLocation());
4561 bool isNestedCapturedVar = false;
4562 if (block)
4563 for (BlockDecl::capture_const_iterator ci = block->capture_begin(),
4564 ce = block->capture_end(); ci != ce; ++ci) {
4565 const VarDecl *variable = ci->getVariable();
4566 if (variable == ND && ci->isNested()) {
4567 assert (ci->isByRef() &&
4568 "SynthBlockInitExpr - captured block variable is not byref");
4569 isNestedCapturedVar = true;
4570 break;
4571 }
4572 }
4573 // captured nested byref variable has its address passed. Do not take
4574 // its address again.
4575 if (!isNestedCapturedVar)
4576 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf,
4577 Context->getPointerType(Exp->getType()),
4578 VK_RValue, OK_Ordinary, SourceLocation());
4579 Exp = NoTypeInfoCStyleCastExpr(Context, castT, CK_BitCast, Exp);
4580 InitExprs.push_back(Exp);
4581 }
4582 }
4583 if (ImportedBlockDecls.size()) {
4584 // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
4585 int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
4586 unsigned IntSize =
4587 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
4588 Expr *FlagExp = IntegerLiteral::Create(*Context, llvm::APInt(IntSize, flag),
4589 Context->IntTy, SourceLocation());
4590 InitExprs.push_back(FlagExp);
4591 }
4592 NewRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0], InitExprs.size(),
4593 FType, VK_LValue, SourceLocation());
4594 NewRep = new (Context) UnaryOperator(NewRep, UO_AddrOf,
4595 Context->getPointerType(NewRep->getType()),
4596 VK_RValue, OK_Ordinary, SourceLocation());
4597 NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CK_BitCast,
4598 NewRep);
4599 BlockDeclRefs.clear();
4600 BlockByRefDecls.clear();
4601 BlockByRefDeclsPtrSet.clear();
4602 BlockByCopyDecls.clear();
4603 BlockByCopyDeclsPtrSet.clear();
4604 ImportedBlockDecls.clear();
4605 return NewRep;
4606}
4607
4608bool RewriteModernObjC::IsDeclStmtInForeachHeader(DeclStmt *DS) {
4609 if (const ObjCForCollectionStmt * CS =
4610 dyn_cast<ObjCForCollectionStmt>(Stmts.back()))
4611 return CS->getElement() == DS;
4612 return false;
4613}
4614
4615//===----------------------------------------------------------------------===//
4616// Function Body / Expression rewriting
4617//===----------------------------------------------------------------------===//
4618
4619Stmt *RewriteModernObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
4620 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
4621 isa<DoStmt>(S) || isa<ForStmt>(S))
4622 Stmts.push_back(S);
4623 else if (isa<ObjCForCollectionStmt>(S)) {
4624 Stmts.push_back(S);
4625 ObjCBcLabelNo.push_back(++BcLabelCount);
4626 }
4627
4628 // Pseudo-object operations and ivar references need special
4629 // treatment because we're going to recursively rewrite them.
4630 if (PseudoObjectExpr *PseudoOp = dyn_cast<PseudoObjectExpr>(S)) {
4631 if (isa<BinaryOperator>(PseudoOp->getSyntacticForm())) {
4632 return RewritePropertyOrImplicitSetter(PseudoOp);
4633 } else {
4634 return RewritePropertyOrImplicitGetter(PseudoOp);
4635 }
4636 } else if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
4637 return RewriteObjCIvarRefExpr(IvarRefExpr);
4638 }
4639
4640 SourceRange OrigStmtRange = S->getSourceRange();
4641
4642 // Perform a bottom up rewrite of all children.
4643 for (Stmt::child_range CI = S->children(); CI; ++CI)
4644 if (*CI) {
4645 Stmt *childStmt = (*CI);
4646 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(childStmt);
4647 if (newStmt) {
4648 *CI = newStmt;
4649 }
4650 }
4651
4652 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
John McCallf4b88a42012-03-10 09:33:50 +00004653 SmallVector<DeclRefExpr *, 8> InnerBlockDeclRefs;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004654 llvm::SmallPtrSet<const DeclContext *, 8> InnerContexts;
4655 InnerContexts.insert(BE->getBlockDecl());
4656 ImportedLocalExternalDecls.clear();
4657 GetInnerBlockDeclRefExprs(BE->getBody(),
4658 InnerBlockDeclRefs, InnerContexts);
4659 // Rewrite the block body in place.
4660 Stmt *SaveCurrentBody = CurrentBody;
4661 CurrentBody = BE->getBody();
4662 PropParentMap = 0;
4663 // block literal on rhs of a property-dot-sytax assignment
4664 // must be replaced by its synthesize ast so getRewrittenText
4665 // works as expected. In this case, what actually ends up on RHS
4666 // is the blockTranscribed which is the helper function for the
4667 // block literal; as in: self.c = ^() {[ace ARR];};
4668 bool saveDisableReplaceStmt = DisableReplaceStmt;
4669 DisableReplaceStmt = false;
4670 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
4671 DisableReplaceStmt = saveDisableReplaceStmt;
4672 CurrentBody = SaveCurrentBody;
4673 PropParentMap = 0;
4674 ImportedLocalExternalDecls.clear();
4675 // Now we snarf the rewritten text and stash it away for later use.
4676 std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
4677 RewrittenBlockExprs[BE] = Str;
4678
4679 Stmt *blockTranscribed = SynthBlockInitExpr(BE, InnerBlockDeclRefs);
4680
4681 //blockTranscribed->dump();
4682 ReplaceStmt(S, blockTranscribed);
4683 return blockTranscribed;
4684 }
4685 // Handle specific things.
4686 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
4687 return RewriteAtEncode(AtEncode);
4688
4689 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
4690 return RewriteAtSelector(AtSelector);
4691
4692 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
4693 return RewriteObjCStringLiteral(AtString);
4694
4695 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
4696#if 0
4697 // Before we rewrite it, put the original message expression in a comment.
4698 SourceLocation startLoc = MessExpr->getLocStart();
4699 SourceLocation endLoc = MessExpr->getLocEnd();
4700
4701 const char *startBuf = SM->getCharacterData(startLoc);
4702 const char *endBuf = SM->getCharacterData(endLoc);
4703
4704 std::string messString;
4705 messString += "// ";
4706 messString.append(startBuf, endBuf-startBuf+1);
4707 messString += "\n";
4708
4709 // FIXME: Missing definition of
4710 // InsertText(clang::SourceLocation, char const*, unsigned int).
4711 // InsertText(startLoc, messString.c_str(), messString.size());
4712 // Tried this, but it didn't work either...
4713 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
4714#endif
4715 return RewriteMessageExpr(MessExpr);
4716 }
4717
4718 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
4719 return RewriteObjCTryStmt(StmtTry);
4720
4721 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
4722 return RewriteObjCSynchronizedStmt(StmtTry);
4723
4724 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
4725 return RewriteObjCThrowStmt(StmtThrow);
4726
4727 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
4728 return RewriteObjCProtocolExpr(ProtocolExp);
4729
4730 if (ObjCForCollectionStmt *StmtForCollection =
4731 dyn_cast<ObjCForCollectionStmt>(S))
4732 return RewriteObjCForCollectionStmt(StmtForCollection,
4733 OrigStmtRange.getEnd());
4734 if (BreakStmt *StmtBreakStmt =
4735 dyn_cast<BreakStmt>(S))
4736 return RewriteBreakStmt(StmtBreakStmt);
4737 if (ContinueStmt *StmtContinueStmt =
4738 dyn_cast<ContinueStmt>(S))
4739 return RewriteContinueStmt(StmtContinueStmt);
4740
4741 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
4742 // and cast exprs.
4743 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
4744 // FIXME: What we're doing here is modifying the type-specifier that
4745 // precedes the first Decl. In the future the DeclGroup should have
4746 // a separate type-specifier that we can rewrite.
4747 // NOTE: We need to avoid rewriting the DeclStmt if it is within
4748 // the context of an ObjCForCollectionStmt. For example:
4749 // NSArray *someArray;
4750 // for (id <FooProtocol> index in someArray) ;
4751 // This is because RewriteObjCForCollectionStmt() does textual rewriting
4752 // and it depends on the original text locations/positions.
4753 if (Stmts.empty() || !IsDeclStmtInForeachHeader(DS))
4754 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
4755
4756 // Blocks rewrite rules.
4757 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
4758 DI != DE; ++DI) {
4759 Decl *SD = *DI;
4760 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
4761 if (isTopLevelBlockPointerType(ND->getType()))
4762 RewriteBlockPointerDecl(ND);
4763 else if (ND->getType()->isFunctionPointerType())
4764 CheckFunctionPointerDecl(ND->getType(), ND);
4765 if (VarDecl *VD = dyn_cast<VarDecl>(SD)) {
4766 if (VD->hasAttr<BlocksAttr>()) {
4767 static unsigned uniqueByrefDeclCount = 0;
4768 assert(!BlockByRefDeclNo.count(ND) &&
4769 "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
4770 BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
4771 RewriteByRefVar(VD);
4772 }
4773 else
4774 RewriteTypeOfDecl(VD);
4775 }
4776 }
4777 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(SD)) {
4778 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
4779 RewriteBlockPointerDecl(TD);
4780 else if (TD->getUnderlyingType()->isFunctionPointerType())
4781 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
4782 }
4783 }
4784 }
4785
4786 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
4787 RewriteObjCQualifiedInterfaceTypes(CE);
4788
4789 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
4790 isa<DoStmt>(S) || isa<ForStmt>(S)) {
4791 assert(!Stmts.empty() && "Statement stack is empty");
4792 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
4793 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
4794 && "Statement stack mismatch");
4795 Stmts.pop_back();
4796 }
4797 // Handle blocks rewriting.
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004798 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4799 ValueDecl *VD = DRE->getDecl();
4800 if (VD->hasAttr<BlocksAttr>())
4801 return RewriteBlockDeclRefExpr(DRE);
4802 if (HasLocalVariableExternalStorage(VD))
4803 return RewriteLocalVariableExternalStorage(DRE);
4804 }
4805
4806 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
4807 if (CE->getCallee()->getType()->isBlockPointerType()) {
4808 Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
4809 ReplaceStmt(S, BlockCall);
4810 return BlockCall;
4811 }
4812 }
4813 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
4814 RewriteCastExpr(CE);
4815 }
4816#if 0
4817 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
4818 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(),
4819 ICE->getSubExpr(),
4820 SourceLocation());
4821 // Get the new text.
4822 std::string SStr;
4823 llvm::raw_string_ostream Buf(SStr);
4824 Replacement->printPretty(Buf, *Context);
4825 const std::string &Str = Buf.str();
4826
4827 printf("CAST = %s\n", &Str[0]);
4828 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
4829 delete S;
4830 return Replacement;
4831 }
4832#endif
4833 // Return this stmt unmodified.
4834 return S;
4835}
4836
4837void RewriteModernObjC::RewriteRecordBody(RecordDecl *RD) {
4838 for (RecordDecl::field_iterator i = RD->field_begin(),
4839 e = RD->field_end(); i != e; ++i) {
4840 FieldDecl *FD = *i;
4841 if (isTopLevelBlockPointerType(FD->getType()))
4842 RewriteBlockPointerDecl(FD);
4843 if (FD->getType()->isObjCQualifiedIdType() ||
4844 FD->getType()->isObjCQualifiedInterfaceType())
4845 RewriteObjCQualifiedInterfaceTypes(FD);
4846 }
4847}
4848
4849/// HandleDeclInMainFile - This is called for each top-level decl defined in the
4850/// main file of the input.
4851void RewriteModernObjC::HandleDeclInMainFile(Decl *D) {
4852 switch (D->getKind()) {
4853 case Decl::Function: {
4854 FunctionDecl *FD = cast<FunctionDecl>(D);
4855 if (FD->isOverloadedOperator())
4856 return;
4857
4858 // Since function prototypes don't have ParmDecl's, we check the function
4859 // prototype. This enables us to rewrite function declarations and
4860 // definitions using the same code.
4861 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
4862
Argyrios Kyrtzidis9335df32012-02-12 04:48:45 +00004863 if (!FD->isThisDeclarationADefinition())
4864 break;
4865
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004866 // FIXME: If this should support Obj-C++, support CXXTryStmt
4867 if (CompoundStmt *Body = dyn_cast_or_null<CompoundStmt>(FD->getBody())) {
4868 CurFunctionDef = FD;
4869 CurFunctionDeclToDeclareForBlock = FD;
4870 CurrentBody = Body;
4871 Body =
4872 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
4873 FD->setBody(Body);
4874 CurrentBody = 0;
4875 if (PropParentMap) {
4876 delete PropParentMap;
4877 PropParentMap = 0;
4878 }
4879 // This synthesizes and inserts the block "impl" struct, invoke function,
4880 // and any copy/dispose helper functions.
4881 InsertBlockLiteralsWithinFunction(FD);
4882 CurFunctionDef = 0;
4883 CurFunctionDeclToDeclareForBlock = 0;
4884 }
4885 break;
4886 }
4887 case Decl::ObjCMethod: {
4888 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(D);
4889 if (CompoundStmt *Body = MD->getCompoundBody()) {
4890 CurMethodDef = MD;
4891 CurrentBody = Body;
4892 Body =
4893 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
4894 MD->setBody(Body);
4895 CurrentBody = 0;
4896 if (PropParentMap) {
4897 delete PropParentMap;
4898 PropParentMap = 0;
4899 }
4900 InsertBlockLiteralsWithinMethod(MD);
4901 CurMethodDef = 0;
4902 }
4903 break;
4904 }
4905 case Decl::ObjCImplementation: {
4906 ObjCImplementationDecl *CI = cast<ObjCImplementationDecl>(D);
4907 ClassImplementation.push_back(CI);
4908 break;
4909 }
4910 case Decl::ObjCCategoryImpl: {
4911 ObjCCategoryImplDecl *CI = cast<ObjCCategoryImplDecl>(D);
4912 CategoryImplementation.push_back(CI);
4913 break;
4914 }
4915 case Decl::Var: {
4916 VarDecl *VD = cast<VarDecl>(D);
4917 RewriteObjCQualifiedInterfaceTypes(VD);
4918 if (isTopLevelBlockPointerType(VD->getType()))
4919 RewriteBlockPointerDecl(VD);
4920 else if (VD->getType()->isFunctionPointerType()) {
4921 CheckFunctionPointerDecl(VD->getType(), VD);
4922 if (VD->getInit()) {
4923 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
4924 RewriteCastExpr(CE);
4925 }
4926 }
4927 } else if (VD->getType()->isRecordType()) {
4928 RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
4929 if (RD->isCompleteDefinition())
4930 RewriteRecordBody(RD);
4931 }
4932 if (VD->getInit()) {
4933 GlobalVarDecl = VD;
4934 CurrentBody = VD->getInit();
4935 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
4936 CurrentBody = 0;
4937 if (PropParentMap) {
4938 delete PropParentMap;
4939 PropParentMap = 0;
4940 }
4941 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(), VD->getName());
4942 GlobalVarDecl = 0;
4943
4944 // This is needed for blocks.
4945 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
4946 RewriteCastExpr(CE);
4947 }
4948 }
4949 break;
4950 }
4951 case Decl::TypeAlias:
4952 case Decl::Typedef: {
4953 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
4954 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
4955 RewriteBlockPointerDecl(TD);
4956 else if (TD->getUnderlyingType()->isFunctionPointerType())
4957 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
4958 }
4959 break;
4960 }
4961 case Decl::CXXRecord:
4962 case Decl::Record: {
4963 RecordDecl *RD = cast<RecordDecl>(D);
4964 if (RD->isCompleteDefinition())
4965 RewriteRecordBody(RD);
4966 break;
4967 }
4968 default:
4969 break;
4970 }
4971 // Nothing yet.
4972}
4973
4974void RewriteModernObjC::HandleTranslationUnit(ASTContext &C) {
4975 if (Diags.hasErrorOccurred())
4976 return;
4977
4978 RewriteInclude();
4979
4980 // Here's a great place to add any extra declarations that may be needed.
4981 // Write out meta data for each @protocol(<expr>).
4982 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
4983 E = ProtocolExprDecls.end(); I != E; ++I)
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00004984 RewriteObjCProtocolMetaData(*I, Preamble);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004985
4986 InsertText(SM->getLocForStartOfFile(MainFileID), Preamble, false);
Fariborz Jahanian57317782012-02-21 23:58:41 +00004987 for (unsigned i = 0, e = ObjCInterfacesSeen.size(); i < e; i++) {
4988 ObjCInterfaceDecl *CDecl = ObjCInterfacesSeen[i];
4989 // Write struct declaration for the class matching its ivar declarations.
4990 // Note that for modern abi, this is postponed until the end of TU
4991 // because class extensions and the implementation might declare their own
4992 // private ivars.
4993 RewriteInterfaceDecl(CDecl);
4994 }
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00004995
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004996 if (ClassImplementation.size() || CategoryImplementation.size())
4997 RewriteImplementations();
4998
4999 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
5000 // we are done.
5001 if (const RewriteBuffer *RewriteBuf =
5002 Rewrite.getRewriteBufferFor(MainFileID)) {
5003 //printf("Changed:\n");
5004 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
5005 } else {
5006 llvm::errs() << "No changes\n";
5007 }
5008
5009 if (ClassImplementation.size() || CategoryImplementation.size() ||
5010 ProtocolExprDecls.size()) {
5011 // Rewrite Objective-c meta data*
5012 std::string ResultStr;
5013 RewriteMetaDataIntoBuffer(ResultStr);
5014 // Emit metadata.
5015 *OutFile << ResultStr;
5016 }
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005017 // Emit ImageInfo;
5018 {
5019 std::string ResultStr;
5020 WriteImageInfo(ResultStr);
5021 *OutFile << ResultStr;
5022 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005023 OutFile->flush();
5024}
5025
5026void RewriteModernObjC::Initialize(ASTContext &context) {
5027 InitializeCommon(context);
5028
Fariborz Jahanian6991bc52012-03-10 17:45:38 +00005029 Preamble += "#ifndef __OBJC2__\n";
5030 Preamble += "#define __OBJC2__\n";
5031 Preamble += "#endif\n";
5032
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005033 // declaring objc_selector outside the parameter list removes a silly
5034 // scope related warning...
5035 if (IsHeader)
5036 Preamble = "#pragma once\n";
5037 Preamble += "struct objc_selector; struct objc_class;\n";
5038 Preamble += "struct __rw_objc_super { struct objc_object *object; ";
5039 Preamble += "struct objc_object *superClass; ";
5040 if (LangOpts.MicrosoftExt) {
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00005041 // Define all sections using syntax that makes sense.
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005042 // These are currently generated.
5043 Preamble += "\n#pragma section(\".objc_classlist$B\", long, read, write)\n";
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00005044 Preamble += "#pragma section(\".objc_catlist$B\", long, read, write)\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005045 Preamble += "#pragma section(\".objc_protolist$B\", long, read, write)\n";
5046 Preamble += "#pragma section(\".objc_imageinfo$B\", long, read, write)\n";
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00005047 Preamble += "#pragma section(\".objc_nlclslist$B\", long, read, write)\n";
5048 Preamble += "#pragma section(\".objc_nlcatlist$B\", long, read, write)\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005049
5050 // These need be generated. But they are not,using API calls instead.
5051 Preamble += "#pragma section(\".objc_selrefs$B\", long, read, write)\n";
5052 Preamble += "#pragma section(\".objc_classrefs$B\", long, read, write)\n";
5053 Preamble += "#pragma section(\".objc_superrefs$B\", long, read, write)\n";
5054
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005055 Preamble += "#pragma section(\".objc_protorefs$B\", long, read, write)\n";
5056
5057
5058 // These are generated but not necessary for functionality.
5059 Preamble += "#pragma section(\".datacoal_nt$B\", long, read, write)\n";
5060 Preamble += "#pragma section(\".cat_cls_meth$B\", long, read, write)\n";
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00005061 Preamble += "#pragma section(\".inst_meth$B\", long, read, write)\n";
5062 Preamble += "#pragma section(\".cls_meth$B\", long, read, write)\n";
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00005063 Preamble += "#pragma section(\".objc_ivar$B\", long, read, write)\n";
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00005064
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005065 // Add a constructor for creating temporary objects.
5066 Preamble += "__rw_objc_super(struct objc_object *o, struct objc_object *s) "
5067 ": ";
5068 Preamble += "object(o), superClass(s) {} ";
5069 }
5070 Preamble += "};\n";
5071 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
5072 Preamble += "typedef struct objc_object Protocol;\n";
5073 Preamble += "#define _REWRITER_typedef_Protocol\n";
5074 Preamble += "#endif\n";
5075 if (LangOpts.MicrosoftExt) {
5076 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
5077 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
5078 } else
5079 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
5080 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend";
5081 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
5082 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper";
5083 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
5084 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object* objc_msgSend_stret";
5085 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
5086 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object* objc_msgSendSuper_stret";
5087 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
5088 Preamble += "__OBJC_RW_DLLIMPORT double objc_msgSend_fpret";
5089 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
5090 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getClass";
5091 Preamble += "(const char *);\n";
5092 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *class_getSuperclass";
5093 Preamble += "(struct objc_class *);\n";
5094 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getMetaClass";
5095 Preamble += "(const char *);\n";
5096 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw(struct objc_object *);\n";
5097 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_enter(void *);\n";
5098 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_exit(void *);\n";
5099 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_exception_extract(void *);\n";
5100 Preamble += "__OBJC_RW_DLLIMPORT int objc_exception_match";
5101 Preamble += "(struct objc_class *, struct objc_object *);\n";
5102 // @synchronized hooks.
5103 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_enter(struct objc_object *);\n";
5104 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_exit(struct objc_object *);\n";
5105 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
5106 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
5107 Preamble += "struct __objcFastEnumerationState {\n\t";
5108 Preamble += "unsigned long state;\n\t";
5109 Preamble += "void **itemsPtr;\n\t";
5110 Preamble += "unsigned long *mutationsPtr;\n\t";
5111 Preamble += "unsigned long extra[5];\n};\n";
5112 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
5113 Preamble += "#define __FASTENUMERATIONSTATE\n";
5114 Preamble += "#endif\n";
5115 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
5116 Preamble += "struct __NSConstantStringImpl {\n";
5117 Preamble += " int *isa;\n";
5118 Preamble += " int flags;\n";
5119 Preamble += " char *str;\n";
5120 Preamble += " long length;\n";
5121 Preamble += "};\n";
5122 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
5123 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
5124 Preamble += "#else\n";
5125 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
5126 Preamble += "#endif\n";
5127 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
5128 Preamble += "#endif\n";
5129 // Blocks preamble.
5130 Preamble += "#ifndef BLOCK_IMPL\n";
5131 Preamble += "#define BLOCK_IMPL\n";
5132 Preamble += "struct __block_impl {\n";
5133 Preamble += " void *isa;\n";
5134 Preamble += " int Flags;\n";
5135 Preamble += " int Reserved;\n";
5136 Preamble += " void *FuncPtr;\n";
5137 Preamble += "};\n";
5138 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
5139 Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
5140 Preamble += "extern \"C\" __declspec(dllexport) "
5141 "void _Block_object_assign(void *, const void *, const int);\n";
5142 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
5143 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
5144 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
5145 Preamble += "#else\n";
5146 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
5147 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
5148 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
5149 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
5150 Preamble += "#endif\n";
5151 Preamble += "#endif\n";
5152 if (LangOpts.MicrosoftExt) {
5153 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
5154 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
5155 Preamble += "#ifndef KEEP_ATTRIBUTES\n"; // We use this for clang tests.
5156 Preamble += "#define __attribute__(X)\n";
5157 Preamble += "#endif\n";
5158 Preamble += "#define __weak\n";
5159 }
5160 else {
5161 Preamble += "#define __block\n";
5162 Preamble += "#define __weak\n";
5163 }
5164 // NOTE! Windows uses LLP64 for 64bit mode. So, cast pointer to long long
5165 // as this avoids warning in any 64bit/32bit compilation model.
5166 Preamble += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long long) &((TYPE *)0)->MEMBER)\n";
5167}
5168
5169/// RewriteIvarOffsetComputation - This rutine synthesizes computation of
5170/// ivar offset.
5171void RewriteModernObjC::RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
5172 std::string &Result) {
5173 if (ivar->isBitField()) {
5174 // FIXME: The hack below doesn't work for bitfields. For now, we simply
5175 // place all bitfields at offset 0.
5176 Result += "0";
5177 } else {
5178 Result += "__OFFSETOFIVAR__(struct ";
5179 Result += ivar->getContainingInterface()->getNameAsString();
5180 if (LangOpts.MicrosoftExt)
5181 Result += "_IMPL";
5182 Result += ", ";
5183 Result += ivar->getNameAsString();
5184 Result += ")";
5185 }
5186}
5187
5188/// WriteModernMetadataDeclarations - Writes out metadata declarations for modern ABI.
5189/// struct _prop_t {
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00005190/// const char *name;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005191/// char *attributes;
5192/// }
5193
5194/// struct _prop_list_t {
5195/// uint32_t entsize; // sizeof(struct _prop_t)
5196/// uint32_t count_of_properties;
5197/// struct _prop_t prop_list[count_of_properties];
5198/// }
5199
5200/// struct _protocol_t;
5201
5202/// struct _protocol_list_t {
5203/// long protocol_count; // Note, this is 32/64 bit
5204/// struct _protocol_t * protocol_list[protocol_count];
5205/// }
5206
5207/// struct _objc_method {
5208/// SEL _cmd;
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005209/// const char *method_type;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005210/// char *_imp;
5211/// }
5212
5213/// struct _method_list_t {
5214/// uint32_t entsize; // sizeof(struct _objc_method)
5215/// uint32_t method_count;
5216/// struct _objc_method method_list[method_count];
5217/// }
5218
5219/// struct _protocol_t {
5220/// id isa; // NULL
5221/// const char * const protocol_name;
5222/// const struct _protocol_list_t * protocol_list; // super protocols
5223/// const struct method_list_t * const instance_methods;
5224/// const struct method_list_t * const class_methods;
5225/// const struct method_list_t *optionalInstanceMethods;
5226/// const struct method_list_t *optionalClassMethods;
5227/// const struct _prop_list_t * properties;
5228/// const uint32_t size; // sizeof(struct _protocol_t)
5229/// const uint32_t flags; // = 0
5230/// const char ** extendedMethodTypes;
5231/// }
5232
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005233/// struct _ivar_t {
5234/// unsigned long int *offset; // pointer to ivar offset location
Fariborz Jahanianae932952012-02-10 20:47:10 +00005235/// const char *name;
5236/// const char *type;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005237/// uint32_t alignment;
5238/// uint32_t size;
5239/// }
5240
5241/// struct _ivar_list_t {
5242/// uint32 entsize; // sizeof(struct _ivar_t)
5243/// uint32 count;
Fariborz Jahanianae932952012-02-10 20:47:10 +00005244/// struct _ivar_t list[count];
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005245/// }
5246
5247/// struct _class_ro_t {
5248/// uint32_t const flags;
5249/// uint32_t const instanceStart;
5250/// uint32_t const instanceSize;
5251/// uint32_t const reserved; // only when building for 64bit targets
5252/// const uint8_t * const ivarLayout;
5253/// const char *const name;
5254/// const struct _method_list_t * const baseMethods;
Fariborz Jahanian0a525342012-02-14 19:31:35 +00005255/// const struct _protocol_list_t *const baseProtocols;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005256/// const struct _ivar_list_t *const ivars;
5257/// const uint8_t * const weakIvarLayout;
5258/// const struct _prop_list_t * const properties;
5259/// }
5260
5261/// struct _class_t {
5262/// struct _class_t *isa;
5263/// struct _class_t * const superclass;
5264/// void *cache;
5265/// IMP *vtable;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005266/// struct _class_ro_t *ro;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005267/// }
5268
5269/// struct _category_t {
5270/// const char * const name;
5271/// struct _class_t *const cls;
5272/// const struct _method_list_t * const instance_methods;
5273/// const struct _method_list_t * const class_methods;
5274/// const struct _protocol_list_t * const protocols;
5275/// const struct _prop_list_t * const properties;
5276/// }
5277
5278/// MessageRefTy - LLVM for:
5279/// struct _message_ref_t {
5280/// IMP messenger;
5281/// SEL name;
5282/// };
5283
5284/// SuperMessageRefTy - LLVM for:
5285/// struct _super_message_ref_t {
5286/// SUPER_IMP messenger;
5287/// SEL name;
5288/// };
5289
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00005290static void WriteModernMetadataDeclarations(ASTContext *Context, std::string &Result) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005291 static bool meta_data_declared = false;
5292 if (meta_data_declared)
5293 return;
5294
5295 Result += "\nstruct _prop_t {\n";
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00005296 Result += "\tconst char *name;\n";
5297 Result += "\tconst char *attributes;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005298 Result += "};\n";
5299
5300 Result += "\nstruct _protocol_t;\n";
5301
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005302 Result += "\nstruct _objc_method {\n";
5303 Result += "\tstruct objc_selector * _cmd;\n";
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005304 Result += "\tconst char *method_type;\n";
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005305 Result += "\tvoid *_imp;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005306 Result += "};\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005307
5308 Result += "\nstruct _protocol_t {\n";
5309 Result += "\tvoid * isa; // NULL\n";
5310 Result += "\tconst char * const protocol_name;\n";
5311 Result += "\tconst struct _protocol_list_t * protocol_list; // super protocols\n";
5312 Result += "\tconst struct method_list_t * const instance_methods;\n";
5313 Result += "\tconst struct method_list_t * const class_methods;\n";
5314 Result += "\tconst struct method_list_t *optionalInstanceMethods;\n";
5315 Result += "\tconst struct method_list_t *optionalClassMethods;\n";
5316 Result += "\tconst struct _prop_list_t * properties;\n";
5317 Result += "\tconst unsigned int size; // sizeof(struct _protocol_t)\n";
5318 Result += "\tconst unsigned int flags; // = 0\n";
5319 Result += "\tconst char ** extendedMethodTypes;\n";
5320 Result += "};\n";
5321
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005322 Result += "\nstruct _ivar_t {\n";
5323 Result += "\tunsigned long int *offset; // pointer to ivar offset location\n";
Fariborz Jahanianae932952012-02-10 20:47:10 +00005324 Result += "\tconst char *name;\n";
5325 Result += "\tconst char *type;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005326 Result += "\tunsigned int alignment;\n";
5327 Result += "\tunsigned int size;\n";
5328 Result += "};\n";
5329
5330 Result += "\nstruct _class_ro_t {\n";
5331 Result += "\tunsigned int const flags;\n";
5332 Result += "\tunsigned int instanceStart;\n";
5333 Result += "\tunsigned int const instanceSize;\n";
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00005334 const llvm::Triple &Triple(Context->getTargetInfo().getTriple());
5335 if (Triple.getArch() == llvm::Triple::x86_64)
5336 Result += "\tunsigned int const reserved;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005337 Result += "\tconst unsigned char * const ivarLayout;\n";
5338 Result += "\tconst char *const name;\n";
5339 Result += "\tconst struct _method_list_t * const baseMethods;\n";
5340 Result += "\tconst struct _objc_protocol_list *const baseProtocols;\n";
5341 Result += "\tconst struct _ivar_list_t *const ivars;\n";
5342 Result += "\tconst unsigned char *const weakIvarLayout;\n";
5343 Result += "\tconst struct _prop_list_t *const properties;\n";
5344 Result += "};\n";
5345
5346 Result += "\nstruct _class_t {\n";
5347 Result += "\tstruct _class_t *isa;\n";
5348 Result += "\tstruct _class_t *const superclass;\n";
5349 Result += "\tvoid *cache;\n";
5350 Result += "\tvoid *vtable;\n";
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005351 Result += "\tstruct _class_ro_t *ro;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005352 Result += "};\n";
5353
5354 Result += "\nstruct _category_t {\n";
5355 Result += "\tconst char * const name;\n";
5356 Result += "\tstruct _class_t *const cls;\n";
5357 Result += "\tconst struct _method_list_t *const instance_methods;\n";
5358 Result += "\tconst struct _method_list_t *const class_methods;\n";
5359 Result += "\tconst struct _protocol_list_t *const protocols;\n";
5360 Result += "\tconst struct _prop_list_t *const properties;\n";
5361 Result += "};\n";
5362
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005363 Result += "extern void *_objc_empty_cache;\n";
5364 Result += "extern void *_objc_empty_vtable;\n";
5365
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005366 meta_data_declared = true;
5367}
5368
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00005369static void Write_protocol_list_t_TypeDecl(std::string &Result,
5370 long super_protocol_count) {
5371 Result += "struct /*_protocol_list_t*/"; Result += " {\n";
5372 Result += "\tlong protocol_count; // Note, this is 32/64 bit\n";
5373 Result += "\tstruct _protocol_t *super_protocols[";
5374 Result += utostr(super_protocol_count); Result += "];\n";
5375 Result += "}";
5376}
5377
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005378static void Write_method_list_t_TypeDecl(std::string &Result,
5379 unsigned int method_count) {
5380 Result += "struct /*_method_list_t*/"; Result += " {\n";
5381 Result += "\tunsigned int entsize; // sizeof(struct _objc_method)\n";
5382 Result += "\tunsigned int method_count;\n";
5383 Result += "\tstruct _objc_method method_list[";
5384 Result += utostr(method_count); Result += "];\n";
5385 Result += "}";
5386}
5387
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00005388static void Write__prop_list_t_TypeDecl(std::string &Result,
5389 unsigned int property_count) {
5390 Result += "struct /*_prop_list_t*/"; Result += " {\n";
5391 Result += "\tunsigned int entsize; // sizeof(struct _prop_t)\n";
5392 Result += "\tunsigned int count_of_properties;\n";
5393 Result += "\tstruct _prop_t prop_list[";
5394 Result += utostr(property_count); Result += "];\n";
5395 Result += "}";
5396}
5397
Fariborz Jahanianae932952012-02-10 20:47:10 +00005398static void Write__ivar_list_t_TypeDecl(std::string &Result,
5399 unsigned int ivar_count) {
5400 Result += "struct /*_ivar_list_t*/"; Result += " {\n";
5401 Result += "\tunsigned int entsize; // sizeof(struct _prop_t)\n";
5402 Result += "\tunsigned int count;\n";
5403 Result += "\tstruct _ivar_t ivar_list[";
5404 Result += utostr(ivar_count); Result += "];\n";
5405 Result += "}";
5406}
5407
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00005408static void Write_protocol_list_initializer(ASTContext *Context, std::string &Result,
5409 ArrayRef<ObjCProtocolDecl *> SuperProtocols,
5410 StringRef VarName,
5411 StringRef ProtocolName) {
5412 if (SuperProtocols.size() > 0) {
5413 Result += "\nstatic ";
5414 Write_protocol_list_t_TypeDecl(Result, SuperProtocols.size());
5415 Result += " "; Result += VarName;
5416 Result += ProtocolName;
5417 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
5418 Result += "\t"; Result += utostr(SuperProtocols.size()); Result += ",\n";
5419 for (unsigned i = 0, e = SuperProtocols.size(); i < e; i++) {
5420 ObjCProtocolDecl *SuperPD = SuperProtocols[i];
5421 Result += "\t&"; Result += "_OBJC_PROTOCOL_";
5422 Result += SuperPD->getNameAsString();
5423 if (i == e-1)
5424 Result += "\n};\n";
5425 else
5426 Result += ",\n";
5427 }
5428 }
5429}
5430
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005431static void Write_method_list_t_initializer(RewriteModernObjC &RewriteObj,
5432 ASTContext *Context, std::string &Result,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005433 ArrayRef<ObjCMethodDecl *> Methods,
5434 StringRef VarName,
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005435 StringRef TopLevelDeclName,
5436 bool MethodImpl) {
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005437 if (Methods.size() > 0) {
5438 Result += "\nstatic ";
5439 Write_method_list_t_TypeDecl(Result, Methods.size());
5440 Result += " "; Result += VarName;
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005441 Result += TopLevelDeclName;
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005442 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
5443 Result += "\t"; Result += "sizeof(_objc_method)"; Result += ",\n";
5444 Result += "\t"; Result += utostr(Methods.size()); Result += ",\n";
5445 for (unsigned i = 0, e = Methods.size(); i < e; i++) {
5446 ObjCMethodDecl *MD = Methods[i];
5447 if (i == 0)
5448 Result += "\t{{(struct objc_selector *)\"";
5449 else
5450 Result += "\t{(struct objc_selector *)\"";
5451 Result += (MD)->getSelector().getAsString(); Result += "\"";
5452 Result += ", ";
5453 std::string MethodTypeString;
5454 Context->getObjCEncodingForMethodDecl(MD, MethodTypeString);
5455 Result += "\""; Result += MethodTypeString; Result += "\"";
5456 Result += ", ";
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005457 if (!MethodImpl)
5458 Result += "0";
5459 else {
5460 Result += "(void *)";
5461 Result += RewriteObj.MethodInternalNames[MD];
5462 }
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005463 if (i == e-1)
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005464 Result += "}}\n";
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005465 else
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005466 Result += "},\n";
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005467 }
5468 Result += "};\n";
5469 }
5470}
5471
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005472static void Write_prop_list_t_initializer(RewriteModernObjC &RewriteObj,
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00005473 ASTContext *Context, std::string &Result,
5474 ArrayRef<ObjCPropertyDecl *> Properties,
5475 const Decl *Container,
5476 StringRef VarName,
5477 StringRef ProtocolName) {
5478 if (Properties.size() > 0) {
5479 Result += "\nstatic ";
5480 Write__prop_list_t_TypeDecl(Result, Properties.size());
5481 Result += " "; Result += VarName;
5482 Result += ProtocolName;
5483 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
5484 Result += "\t"; Result += "sizeof(_prop_t)"; Result += ",\n";
5485 Result += "\t"; Result += utostr(Properties.size()); Result += ",\n";
5486 for (unsigned i = 0, e = Properties.size(); i < e; i++) {
5487 ObjCPropertyDecl *PropDecl = Properties[i];
5488 if (i == 0)
5489 Result += "\t{{\"";
5490 else
5491 Result += "\t{\"";
5492 Result += PropDecl->getName(); Result += "\",";
5493 std::string PropertyTypeString, QuotePropertyTypeString;
5494 Context->getObjCEncodingForPropertyDecl(PropDecl, Container, PropertyTypeString);
5495 RewriteObj.QuoteDoublequotes(PropertyTypeString, QuotePropertyTypeString);
5496 Result += "\""; Result += QuotePropertyTypeString; Result += "\"";
5497 if (i == e-1)
5498 Result += "}}\n";
5499 else
5500 Result += "},\n";
5501 }
5502 Result += "};\n";
5503 }
5504}
5505
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00005506// Metadata flags
5507enum MetaDataDlags {
5508 CLS = 0x0,
5509 CLS_META = 0x1,
5510 CLS_ROOT = 0x2,
5511 OBJC2_CLS_HIDDEN = 0x10,
5512 CLS_EXCEPTION = 0x20,
5513
5514 /// (Obsolete) ARC-specific: this class has a .release_ivars method
5515 CLS_HAS_IVAR_RELEASER = 0x40,
5516 /// class was compiled with -fobjc-arr
5517 CLS_COMPILED_BY_ARC = 0x80 // (1<<7)
5518};
5519
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005520static void Write__class_ro_t_initializer(ASTContext *Context, std::string &Result,
5521 unsigned int flags,
5522 const std::string &InstanceStart,
5523 const std::string &InstanceSize,
5524 ArrayRef<ObjCMethodDecl *>baseMethods,
5525 ArrayRef<ObjCProtocolDecl *>baseProtocols,
5526 ArrayRef<ObjCIvarDecl *>ivars,
5527 ArrayRef<ObjCPropertyDecl *>Properties,
5528 StringRef VarName,
5529 StringRef ClassName) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005530 Result += "\nstatic struct _class_ro_t ";
5531 Result += VarName; Result += ClassName;
5532 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
5533 Result += "\t";
5534 Result += llvm::utostr(flags); Result += ", ";
5535 Result += InstanceStart; Result += ", ";
5536 Result += InstanceSize; Result += ", \n";
5537 Result += "\t";
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00005538 const llvm::Triple &Triple(Context->getTargetInfo().getTriple());
5539 if (Triple.getArch() == llvm::Triple::x86_64)
5540 // uint32_t const reserved; // only when building for 64bit targets
5541 Result += "(unsigned int)0, \n\t";
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005542 // const uint8_t * const ivarLayout;
5543 Result += "0, \n\t";
5544 Result += "\""; Result += ClassName; Result += "\",\n\t";
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00005545 bool metaclass = ((flags & CLS_META) != 0);
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005546 if (baseMethods.size() > 0) {
5547 Result += "(const struct _method_list_t *)&";
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00005548 if (metaclass)
5549 Result += "_OBJC_$_CLASS_METHODS_";
5550 else
5551 Result += "_OBJC_$_INSTANCE_METHODS_";
5552 Result += ClassName;
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005553 Result += ",\n\t";
5554 }
5555 else
5556 Result += "0, \n\t";
5557
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00005558 if (!metaclass && baseProtocols.size() > 0) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005559 Result += "(const struct _objc_protocol_list *)&";
5560 Result += "_OBJC_CLASS_PROTOCOLS_$_"; Result += ClassName;
5561 Result += ",\n\t";
5562 }
5563 else
5564 Result += "0, \n\t";
5565
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00005566 if (!metaclass && ivars.size() > 0) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005567 Result += "(const struct _ivar_list_t *)&";
5568 Result += "_OBJC_$_INSTANCE_VARIABLES_"; Result += ClassName;
5569 Result += ",\n\t";
5570 }
5571 else
5572 Result += "0, \n\t";
5573
5574 // weakIvarLayout
5575 Result += "0, \n\t";
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00005576 if (!metaclass && Properties.size() > 0) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005577 Result += "(const struct _prop_list_t *)&";
Fariborz Jahanianeeabf382012-02-16 21:57:59 +00005578 Result += "_OBJC_$_PROP_LIST_"; Result += ClassName;
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005579 Result += ",\n";
5580 }
5581 else
5582 Result += "0, \n";
5583
5584 Result += "};\n";
5585}
5586
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005587static void Write_class_t(ASTContext *Context, std::string &Result,
5588 StringRef VarName,
5589 const ObjCInterfaceDecl *CDecl, bool metadata) {
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005590
5591 if (metadata && !CDecl->getSuperClass()) {
5592 // Need to handle a case of use of forward declaration.
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00005593 Result += "\n";
5594 if (CDecl->getImplementation())
5595 Result += "__declspec(dllexport) ";
5596 Result += "extern struct _class_t OBJC_CLASS_$_";
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005597 Result += CDecl->getNameAsString();
5598 Result += ";\n";
5599 }
5600 // Also, for possibility of 'super' metadata class not having been defined yet.
5601 if (CDecl->getSuperClass()) {
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00005602 Result += "\n";
5603 if (CDecl->getSuperClass()->getImplementation())
5604 Result += "__declspec(dllexport) ";
5605 Result += "extern struct _class_t ";
5606 Result += VarName;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005607 Result += CDecl->getSuperClass()->getNameAsString();
5608 Result += ";\n";
5609 }
5610
Fariborz Jahaniane57303c2012-03-10 00:39:34 +00005611 Result += "\n__declspec(dllexport) struct _class_t "; Result += VarName; Result += CDecl->getNameAsString();
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005612 Result += " __attribute__ ((used, section (\"__DATA,__objc_data\"))) = {\n";
5613 Result += "\t";
5614 if (metadata) {
5615 if (CDecl->getSuperClass()) {
5616 Result += "&"; Result += VarName;
5617 Result += CDecl->getSuperClass()->getNameAsString();
5618 Result += ",\n\t";
5619 Result += "&"; Result += VarName;
5620 Result += CDecl->getSuperClass()->getNameAsString();
5621 Result += ",\n\t";
5622 }
5623 else {
5624 Result += "&"; Result += VarName;
5625 Result += CDecl->getNameAsString();
5626 Result += ",\n\t";
5627 Result += "&OBJC_CLASS_$_"; Result += CDecl->getNameAsString();
5628 Result += ",\n\t";
5629 }
5630 }
5631 else {
5632 Result += "&OBJC_METACLASS_$_";
5633 Result += CDecl->getNameAsString();
5634 Result += ",\n\t";
5635 if (CDecl->getSuperClass()) {
5636 Result += "&"; Result += VarName;
5637 Result += CDecl->getSuperClass()->getNameAsString();
5638 Result += ",\n\t";
5639 }
5640 else
5641 Result += "0,\n\t";
5642 }
5643 Result += "(void *)&_objc_empty_cache,\n\t";
5644 Result += "(void *)&_objc_empty_vtable,\n\t";
5645 if (metadata)
5646 Result += "&_OBJC_METACLASS_RO_$_";
5647 else
5648 Result += "&_OBJC_CLASS_RO_$_";
5649 Result += CDecl->getNameAsString();
5650 Result += ",\n};\n";
5651}
5652
Fariborz Jahanian61186122012-02-17 18:40:41 +00005653static void Write_category_t(RewriteModernObjC &RewriteObj, ASTContext *Context,
5654 std::string &Result,
5655 StringRef CatName,
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00005656 ObjCInterfaceDecl *ClassDecl,
Fariborz Jahanian61186122012-02-17 18:40:41 +00005657 ArrayRef<ObjCMethodDecl *> InstanceMethods,
5658 ArrayRef<ObjCMethodDecl *> ClassMethods,
5659 ArrayRef<ObjCProtocolDecl *> RefedProtocols,
5660 ArrayRef<ObjCPropertyDecl *> ClassProperties) {
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00005661
5662 StringRef ClassName = ClassDecl->getNameAsString();
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00005663 // must declare an extern class object in case this class is not implemented
5664 // in this TU.
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00005665 Result += "\n";
5666 if (ClassDecl->getImplementation())
5667 Result += "__declspec(dllexport) ";
5668
5669 Result += "extern struct _class_t ";
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00005670 Result += "OBJC_CLASS_$_"; Result += ClassName;
5671 Result += ";\n";
5672
Fariborz Jahanian61186122012-02-17 18:40:41 +00005673 Result += "\nstatic struct _category_t ";
5674 Result += "_OBJC_$_CATEGORY_";
5675 Result += ClassName; Result += "_$_"; Result += CatName;
5676 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = \n";
5677 Result += "{\n";
5678 Result += "\t\""; Result += ClassName; Result += "\",\n";
5679 Result += "\t&"; Result += "OBJC_CLASS_$_"; Result += ClassName;
5680 Result += ",\n";
5681 if (InstanceMethods.size() > 0) {
5682 Result += "\t(const struct _method_list_t *)&";
5683 Result += "_OBJC_$_CATEGORY_INSTANCE_METHODS_";
5684 Result += ClassName; Result += "_$_"; Result += CatName;
5685 Result += ",\n";
5686 }
5687 else
5688 Result += "\t0,\n";
5689
5690 if (ClassMethods.size() > 0) {
5691 Result += "\t(const struct _method_list_t *)&";
5692 Result += "_OBJC_$_CATEGORY_CLASS_METHODS_";
5693 Result += ClassName; Result += "_$_"; Result += CatName;
5694 Result += ",\n";
5695 }
5696 else
5697 Result += "\t0,\n";
5698
5699 if (RefedProtocols.size() > 0) {
5700 Result += "\t(const struct _protocol_list_t *)&";
5701 Result += "_OBJC_CATEGORY_PROTOCOLS_$_";
5702 Result += ClassName; Result += "_$_"; Result += CatName;
5703 Result += ",\n";
5704 }
5705 else
5706 Result += "\t0,\n";
5707
5708 if (ClassProperties.size() > 0) {
5709 Result += "\t(const struct _prop_list_t *)&"; Result += "_OBJC_$_PROP_LIST_";
5710 Result += ClassName; Result += "_$_"; Result += CatName;
5711 Result += ",\n";
5712 }
5713 else
5714 Result += "\t0,\n";
5715
5716 Result += "};\n";
5717}
5718
Fariborz Jahaniane0adbd82012-02-08 22:23:26 +00005719static void Write__extendedMethodTypes_initializer(RewriteModernObjC &RewriteObj,
5720 ASTContext *Context, std::string &Result,
5721 ArrayRef<ObjCMethodDecl *> Methods,
5722 StringRef VarName,
5723 StringRef ProtocolName) {
5724 if (Methods.size() == 0)
5725 return;
5726
5727 Result += "\nstatic const char *";
5728 Result += VarName; Result += ProtocolName;
5729 Result += " [] __attribute__ ((used, section (\"__DATA,__objc_const\"))) = \n";
5730 Result += "{\n";
5731 for (unsigned i = 0, e = Methods.size(); i < e; i++) {
5732 ObjCMethodDecl *MD = Methods[i];
5733 std::string MethodTypeString, QuoteMethodTypeString;
5734 Context->getObjCEncodingForMethodDecl(MD, MethodTypeString, true);
5735 RewriteObj.QuoteDoublequotes(MethodTypeString, QuoteMethodTypeString);
5736 Result += "\t\""; Result += QuoteMethodTypeString; Result += "\"";
5737 if (i == e-1)
5738 Result += "\n};\n";
5739 else {
5740 Result += ",\n";
5741 }
5742 }
5743}
5744
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00005745static void Write_IvarOffsetVar(ASTContext *Context,
5746 std::string &Result,
Fariborz Jahaniandb649232012-02-13 20:59:02 +00005747 ArrayRef<ObjCIvarDecl *> Ivars,
5748 StringRef VarName,
5749 StringRef ClassName) {
5750 // FIXME. visibilty of offset symbols may have to be set; for Darwin
5751 // this is what happens:
5752 /**
5753 if (Ivar->getAccessControl() == ObjCIvarDecl::Private ||
5754 Ivar->getAccessControl() == ObjCIvarDecl::Package ||
5755 Class->getVisibility() == HiddenVisibility)
5756 Visibility shoud be: HiddenVisibility;
5757 else
5758 Visibility shoud be: DefaultVisibility;
5759 */
5760
Fariborz Jahanian07e52882012-02-13 21:34:45 +00005761 Result += "\n";
5762 for (unsigned i =0, e = Ivars.size(); i < e; i++) {
5763 ObjCIvarDecl *IvarDecl = Ivars[i];
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00005764 if (Context->getLangOpts().MicrosoftExt)
5765 Result += "__declspec(allocate(\".objc_ivar$B\")) ";
5766
5767 if (!Context->getLangOpts().MicrosoftExt ||
5768 IvarDecl->getAccessControl() == ObjCIvarDecl::Private ||
Fariborz Jahanian117591f2012-03-10 01:34:42 +00005769 IvarDecl->getAccessControl() == ObjCIvarDecl::Package)
Fariborz Jahaniand1c84d32012-03-10 00:53:02 +00005770 Result += "unsigned long int ";
5771 else
5772 Result += "__declspec(dllexport) unsigned long int ";
5773
5774 Result += VarName;
Fariborz Jahanian07e52882012-02-13 21:34:45 +00005775 Result += ClassName; Result += "_";
5776 Result += IvarDecl->getName();
5777 Result += " __attribute__ ((used, section (\"__DATA,__objc_ivar\")))";
5778 Result += " = ";
5779 if (IvarDecl->isBitField()) {
5780 // FIXME: The hack below doesn't work for bitfields. For now, we simply
5781 // place all bitfields at offset 0.
5782 Result += "0;\n";
5783 }
5784 else {
Fariborz Jahaniandb649232012-02-13 20:59:02 +00005785 Result += "__OFFSETOFIVAR__(struct ";
5786 Result += ClassName;
5787 Result += "_IMPL, ";
5788 Result += IvarDecl->getName(); Result += ");\n";
5789 }
5790 }
5791}
5792
Fariborz Jahanianae932952012-02-10 20:47:10 +00005793static void Write__ivar_list_t_initializer(RewriteModernObjC &RewriteObj,
5794 ASTContext *Context, std::string &Result,
5795 ArrayRef<ObjCIvarDecl *> Ivars,
5796 StringRef VarName,
5797 StringRef ClassName) {
5798 if (Ivars.size() > 0) {
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00005799 Write_IvarOffsetVar(Context, Result, Ivars, "OBJC_IVAR_$_", ClassName);
Fariborz Jahanian07e52882012-02-13 21:34:45 +00005800
Fariborz Jahanianae932952012-02-10 20:47:10 +00005801 Result += "\nstatic ";
5802 Write__ivar_list_t_TypeDecl(Result, Ivars.size());
5803 Result += " "; Result += VarName;
5804 Result += ClassName;
5805 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
5806 Result += "\t"; Result += "sizeof(_ivar_t)"; Result += ",\n";
5807 Result += "\t"; Result += utostr(Ivars.size()); Result += ",\n";
5808 for (unsigned i =0, e = Ivars.size(); i < e; i++) {
5809 ObjCIvarDecl *IvarDecl = Ivars[i];
5810 if (i == 0)
5811 Result += "\t{{";
5812 else
5813 Result += "\t {";
Fariborz Jahaniandb649232012-02-13 20:59:02 +00005814
5815 Result += "(unsigned long int *)&OBJC_IVAR_$_";
5816 Result += ClassName; Result += "_"; Result += IvarDecl->getName();
5817 Result += ", ";
Fariborz Jahanianae932952012-02-10 20:47:10 +00005818
5819 Result += "\""; Result += IvarDecl->getName(); Result += "\", ";
5820 std::string IvarTypeString, QuoteIvarTypeString;
5821 Context->getObjCEncodingForType(IvarDecl->getType(), IvarTypeString,
5822 IvarDecl);
5823 RewriteObj.QuoteDoublequotes(IvarTypeString, QuoteIvarTypeString);
5824 Result += "\""; Result += QuoteIvarTypeString; Result += "\", ";
5825
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00005826 // FIXME. this alignment represents the host alignment and need be changed to
5827 // represent the target alignment.
5828 unsigned Align = Context->getTypeAlign(IvarDecl->getType())/8;
5829 Align = llvm::Log2_32(Align);
Fariborz Jahanianae932952012-02-10 20:47:10 +00005830 Result += llvm::utostr(Align); Result += ", ";
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00005831 CharUnits Size = Context->getTypeSizeInChars(IvarDecl->getType());
5832 Result += llvm::utostr(Size.getQuantity());
Fariborz Jahanianae932952012-02-10 20:47:10 +00005833 if (i == e-1)
5834 Result += "}}\n";
5835 else
5836 Result += "},\n";
5837 }
5838 Result += "};\n";
5839 }
5840}
5841
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005842/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00005843void RewriteModernObjC::RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl,
5844 std::string &Result) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005845
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005846 // Do not synthesize the protocol more than once.
5847 if (ObjCSynthesizedProtocols.count(PDecl->getCanonicalDecl()))
5848 return;
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00005849 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005850
5851 if (ObjCProtocolDecl *Def = PDecl->getDefinition())
5852 PDecl = Def;
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00005853 // Must write out all protocol definitions in current qualifier list,
5854 // and in their nested qualifiers before writing out current definition.
5855 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
5856 E = PDecl->protocol_end(); I != E; ++I)
5857 RewriteObjCProtocolMetaData(*I, Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005858
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005859 // Construct method lists.
5860 std::vector<ObjCMethodDecl *> InstanceMethods, ClassMethods;
5861 std::vector<ObjCMethodDecl *> OptInstanceMethods, OptClassMethods;
5862 for (ObjCProtocolDecl::instmeth_iterator
5863 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
5864 I != E; ++I) {
5865 ObjCMethodDecl *MD = *I;
5866 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
5867 OptInstanceMethods.push_back(MD);
5868 } else {
5869 InstanceMethods.push_back(MD);
5870 }
5871 }
5872
5873 for (ObjCProtocolDecl::classmeth_iterator
5874 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
5875 I != E; ++I) {
5876 ObjCMethodDecl *MD = *I;
5877 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
5878 OptClassMethods.push_back(MD);
5879 } else {
5880 ClassMethods.push_back(MD);
5881 }
5882 }
Fariborz Jahaniane0adbd82012-02-08 22:23:26 +00005883 std::vector<ObjCMethodDecl *> AllMethods;
5884 for (unsigned i = 0, e = InstanceMethods.size(); i < e; i++)
5885 AllMethods.push_back(InstanceMethods[i]);
5886 for (unsigned i = 0, e = ClassMethods.size(); i < e; i++)
5887 AllMethods.push_back(ClassMethods[i]);
5888 for (unsigned i = 0, e = OptInstanceMethods.size(); i < e; i++)
5889 AllMethods.push_back(OptInstanceMethods[i]);
5890 for (unsigned i = 0, e = OptClassMethods.size(); i < e; i++)
5891 AllMethods.push_back(OptClassMethods[i]);
5892
5893 Write__extendedMethodTypes_initializer(*this, Context, Result,
5894 AllMethods,
5895 "_OBJC_PROTOCOL_METHOD_TYPES_",
5896 PDecl->getNameAsString());
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00005897 // Protocol's super protocol list
5898 std::vector<ObjCProtocolDecl *> SuperProtocols;
5899 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
5900 E = PDecl->protocol_end(); I != E; ++I)
5901 SuperProtocols.push_back(*I);
5902
5903 Write_protocol_list_initializer(Context, Result, SuperProtocols,
5904 "_OBJC_PROTOCOL_REFS_",
5905 PDecl->getNameAsString());
5906
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005907 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005908 "_OBJC_PROTOCOL_INSTANCE_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005909 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005910
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005911 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005912 "_OBJC_PROTOCOL_CLASS_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005913 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005914
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005915 Write_method_list_t_initializer(*this, Context, Result, OptInstanceMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005916 "_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005917 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005918
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005919 Write_method_list_t_initializer(*this, Context, Result, OptClassMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005920 "_OBJC_PROTOCOL_OPT_CLASS_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005921 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005922
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00005923 // Protocol's property metadata.
5924 std::vector<ObjCPropertyDecl *> ProtocolProperties;
5925 for (ObjCContainerDecl::prop_iterator I = PDecl->prop_begin(),
5926 E = PDecl->prop_end(); I != E; ++I)
5927 ProtocolProperties.push_back(*I);
5928
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005929 Write_prop_list_t_initializer(*this, Context, Result, ProtocolProperties,
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00005930 /* Container */0,
5931 "_OBJC_PROTOCOL_PROPERTIES_",
5932 PDecl->getNameAsString());
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00005933
Fariborz Jahanian82848c22012-02-08 00:50:52 +00005934 // Writer out root metadata for current protocol: struct _protocol_t
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00005935 Result += "\n";
5936 if (LangOpts.MicrosoftExt)
5937 Result += "__declspec(allocate(\".datacoal_nt$B\")) ";
5938 Result += "static struct _protocol_t _OBJC_PROTOCOL_";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005939 Result += PDecl->getNameAsString();
Fariborz Jahanian82848c22012-02-08 00:50:52 +00005940 Result += " __attribute__ ((used, section (\"__DATA,__datacoal_nt,coalesced\"))) = {\n";
5941 Result += "\t0,\n"; // id is; is null
5942 Result += "\t\""; Result += PDecl->getNameAsString(); Result += "\",\n";
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00005943 if (SuperProtocols.size() > 0) {
5944 Result += "\t(const struct _protocol_list_t *)&"; Result += "_OBJC_PROTOCOL_REFS_";
5945 Result += PDecl->getNameAsString(); Result += ",\n";
5946 }
5947 else
5948 Result += "\t0,\n";
Fariborz Jahanian82848c22012-02-08 00:50:52 +00005949 if (InstanceMethods.size() > 0) {
5950 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
5951 Result += PDecl->getNameAsString(); Result += ",\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005952 }
5953 else
Fariborz Jahanian82848c22012-02-08 00:50:52 +00005954 Result += "\t0,\n";
5955
5956 if (ClassMethods.size() > 0) {
5957 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_CLASS_METHODS_";
5958 Result += PDecl->getNameAsString(); Result += ",\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005959 }
5960 else
Fariborz Jahanian82848c22012-02-08 00:50:52 +00005961 Result += "\t0,\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005962
Fariborz Jahanian82848c22012-02-08 00:50:52 +00005963 if (OptInstanceMethods.size() > 0) {
5964 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_";
5965 Result += PDecl->getNameAsString(); Result += ",\n";
5966 }
5967 else
5968 Result += "\t0,\n";
5969
5970 if (OptClassMethods.size() > 0) {
5971 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_CLASS_METHODS_";
5972 Result += PDecl->getNameAsString(); Result += ",\n";
5973 }
5974 else
5975 Result += "\t0,\n";
5976
5977 if (ProtocolProperties.size() > 0) {
5978 Result += "\t(const struct _prop_list_t *)&_OBJC_PROTOCOL_PROPERTIES_";
5979 Result += PDecl->getNameAsString(); Result += ",\n";
5980 }
5981 else
5982 Result += "\t0,\n";
5983
5984 Result += "\t"; Result += "sizeof(_protocol_t)"; Result += ",\n";
5985 Result += "\t0,\n";
5986
Fariborz Jahaniane0adbd82012-02-08 22:23:26 +00005987 if (AllMethods.size() > 0) {
5988 Result += "\t(const char **)&"; Result += "_OBJC_PROTOCOL_METHOD_TYPES_";
5989 Result += PDecl->getNameAsString();
5990 Result += "\n};\n";
5991 }
5992 else
5993 Result += "\t0\n};\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005994
5995 // Use this protocol meta-data to build protocol list table in section
5996 // .objc_protolist$B
5997 // Unspecified visibility means 'private extern'.
5998 if (LangOpts.MicrosoftExt)
5999 Result += "__declspec(allocate(\".objc_protolist$B\")) ";
6000 Result += "struct _protocol_t *";
6001 Result += "_OBJC_LABEL_PROTOCOL_$_"; Result += PDecl->getNameAsString();
6002 Result += " = &_OBJC_PROTOCOL_"; Result += PDecl->getNameAsString();
6003 Result += ";\n";
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006004
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006005 // Mark this protocol as having been generated.
6006 if (!ObjCSynthesizedProtocols.insert(PDecl->getCanonicalDecl()))
6007 llvm_unreachable("protocol already synthesized");
6008
6009}
6010
6011void RewriteModernObjC::RewriteObjCProtocolListMetaData(
6012 const ObjCList<ObjCProtocolDecl> &Protocols,
6013 StringRef prefix, StringRef ClassName,
6014 std::string &Result) {
6015 if (Protocols.empty()) return;
6016
6017 for (unsigned i = 0; i != Protocols.size(); i++)
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006018 RewriteObjCProtocolMetaData(Protocols[i], Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006019
6020 // Output the top lovel protocol meta-data for the class.
6021 /* struct _objc_protocol_list {
6022 struct _objc_protocol_list *next;
6023 int protocol_count;
6024 struct _objc_protocol *class_protocols[];
6025 }
6026 */
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00006027 Result += "\n";
6028 if (LangOpts.MicrosoftExt)
6029 Result += "__declspec(allocate(\".cat_cls_meth$B\")) ";
6030 Result += "static struct {\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006031 Result += "\tstruct _objc_protocol_list *next;\n";
6032 Result += "\tint protocol_count;\n";
6033 Result += "\tstruct _objc_protocol *class_protocols[";
6034 Result += utostr(Protocols.size());
6035 Result += "];\n} _OBJC_";
6036 Result += prefix;
6037 Result += "_PROTOCOLS_";
6038 Result += ClassName;
6039 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
6040 "{\n\t0, ";
6041 Result += utostr(Protocols.size());
6042 Result += "\n";
6043
6044 Result += "\t,{&_OBJC_PROTOCOL_";
6045 Result += Protocols[0]->getNameAsString();
6046 Result += " \n";
6047
6048 for (unsigned i = 1; i != Protocols.size(); i++) {
6049 Result += "\t ,&_OBJC_PROTOCOL_";
6050 Result += Protocols[i]->getNameAsString();
6051 Result += "\n";
6052 }
6053 Result += "\t }\n};\n";
6054}
6055
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006056/// hasObjCExceptionAttribute - Return true if this class or any super
6057/// class has the __objc_exception__ attribute.
6058/// FIXME. Move this to ASTContext.cpp as it is also used for IRGen.
6059static bool hasObjCExceptionAttribute(ASTContext &Context,
6060 const ObjCInterfaceDecl *OID) {
6061 if (OID->hasAttr<ObjCExceptionAttr>())
6062 return true;
6063 if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
6064 return hasObjCExceptionAttribute(Context, Super);
6065 return false;
6066}
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006067
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006068void RewriteModernObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
6069 std::string &Result) {
6070 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
6071
6072 // Explicitly declared @interface's are already synthesized.
Fariborz Jahanianae932952012-02-10 20:47:10 +00006073 if (CDecl->isImplicitInterfaceDecl())
6074 assert(false &&
6075 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00006076
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00006077 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanianae932952012-02-10 20:47:10 +00006078 SmallVector<ObjCIvarDecl *, 8> IVars;
6079
6080 for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
6081 IVD; IVD = IVD->getNextIvar()) {
6082 // Ignore unnamed bit-fields.
6083 if (!IVD->getDeclName())
6084 continue;
6085 IVars.push_back(IVD);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006086 }
6087
Fariborz Jahanianae932952012-02-10 20:47:10 +00006088 Write__ivar_list_t_initializer(*this, Context, Result, IVars,
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006089 "_OBJC_$_INSTANCE_VARIABLES_",
Fariborz Jahanianae932952012-02-10 20:47:10 +00006090 CDecl->getNameAsString());
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006091
6092 // Build _objc_method_list for class's instance methods if needed
6093 SmallVector<ObjCMethodDecl *, 32>
6094 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
6095
6096 // If any of our property implementations have associated getters or
6097 // setters, produce metadata for them as well.
6098 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
6099 PropEnd = IDecl->propimpl_end();
6100 Prop != PropEnd; ++Prop) {
6101 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
6102 continue;
6103 if (!(*Prop)->getPropertyIvarDecl())
6104 continue;
6105 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
6106 if (!PD)
6107 continue;
6108 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
6109 if (!Getter->isDefined())
6110 InstanceMethods.push_back(Getter);
6111 if (PD->isReadOnly())
6112 continue;
6113 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
6114 if (!Setter->isDefined())
6115 InstanceMethods.push_back(Setter);
6116 }
6117
6118 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
6119 "_OBJC_$_INSTANCE_METHODS_",
6120 IDecl->getNameAsString(), true);
6121
6122 SmallVector<ObjCMethodDecl *, 32>
6123 ClassMethods(IDecl->classmeth_begin(), IDecl->classmeth_end());
6124
6125 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
6126 "_OBJC_$_CLASS_METHODS_",
6127 IDecl->getNameAsString(), true);
Fariborz Jahanian0a525342012-02-14 19:31:35 +00006128
6129 // Protocols referenced in class declaration?
6130 // Protocol's super protocol list
6131 std::vector<ObjCProtocolDecl *> RefedProtocols;
6132 const ObjCList<ObjCProtocolDecl> &Protocols = CDecl->getReferencedProtocols();
6133 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
6134 E = Protocols.end();
6135 I != E; ++I) {
6136 RefedProtocols.push_back(*I);
6137 // Must write out all protocol definitions in current qualifier list,
6138 // and in their nested qualifiers before writing out current definition.
6139 RewriteObjCProtocolMetaData(*I, Result);
6140 }
6141
6142 Write_protocol_list_initializer(Context, Result,
6143 RefedProtocols,
6144 "_OBJC_CLASS_PROTOCOLS_$_",
6145 IDecl->getNameAsString());
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006146
6147 // Protocol's property metadata.
6148 std::vector<ObjCPropertyDecl *> ClassProperties;
6149 for (ObjCContainerDecl::prop_iterator I = CDecl->prop_begin(),
6150 E = CDecl->prop_end(); I != E; ++I)
6151 ClassProperties.push_back(*I);
6152
6153 Write_prop_list_t_initializer(*this, Context, Result, ClassProperties,
6154 /* Container */0,
Fariborz Jahanianeeabf382012-02-16 21:57:59 +00006155 "_OBJC_$_PROP_LIST_",
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006156 CDecl->getNameAsString());
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006157
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006158
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006159 // Data for initializing _class_ro_t metaclass meta-data
6160 uint32_t flags = CLS_META;
6161 std::string InstanceSize;
6162 std::string InstanceStart;
6163
6164
6165 bool classIsHidden = CDecl->getVisibility() == HiddenVisibility;
6166 if (classIsHidden)
6167 flags |= OBJC2_CLS_HIDDEN;
6168
6169 if (!CDecl->getSuperClass())
6170 // class is root
6171 flags |= CLS_ROOT;
6172 InstanceSize = "sizeof(struct _class_t)";
6173 InstanceStart = InstanceSize;
6174 Write__class_ro_t_initializer(Context, Result, flags,
6175 InstanceStart, InstanceSize,
6176 ClassMethods,
6177 0,
6178 0,
6179 0,
6180 "_OBJC_METACLASS_RO_$_",
6181 CDecl->getNameAsString());
6182
6183
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006184 // Data for initializing _class_ro_t meta-data
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006185 flags = CLS;
6186 if (classIsHidden)
6187 flags |= OBJC2_CLS_HIDDEN;
6188
6189 if (hasObjCExceptionAttribute(*Context, CDecl))
6190 flags |= CLS_EXCEPTION;
6191
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006192 if (!CDecl->getSuperClass())
6193 // class is root
6194 flags |= CLS_ROOT;
6195
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006196 InstanceSize.clear();
6197 InstanceStart.clear();
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006198 if (!ObjCSynthesizedStructs.count(CDecl)) {
6199 InstanceSize = "0";
6200 InstanceStart = "0";
6201 }
6202 else {
6203 InstanceSize = "sizeof(struct ";
6204 InstanceSize += CDecl->getNameAsString();
6205 InstanceSize += "_IMPL)";
6206
6207 ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
6208 if (IVD) {
6209 InstanceStart += "__OFFSETOFIVAR__(struct ";
6210 InstanceStart += CDecl->getNameAsString();
6211 InstanceStart += "_IMPL, ";
6212 InstanceStart += IVD->getNameAsString();
6213 InstanceStart += ")";
6214 }
6215 else
6216 InstanceStart = InstanceSize;
6217 }
6218 Write__class_ro_t_initializer(Context, Result, flags,
6219 InstanceStart, InstanceSize,
6220 InstanceMethods,
6221 RefedProtocols,
6222 IVars,
6223 ClassProperties,
6224 "_OBJC_CLASS_RO_$_",
6225 CDecl->getNameAsString());
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006226
6227 Write_class_t(Context, Result,
6228 "OBJC_METACLASS_$_",
6229 CDecl, /*metaclass*/true);
6230
6231 Write_class_t(Context, Result,
6232 "OBJC_CLASS_$_",
6233 CDecl, /*metaclass*/false);
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006234
6235 if (ImplementationIsNonLazy(IDecl))
6236 DefinedNonLazyClasses.push_back(CDecl);
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006237
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006238}
6239
6240void RewriteModernObjC::RewriteMetaDataIntoBuffer(std::string &Result) {
6241 int ClsDefCount = ClassImplementation.size();
6242 int CatDefCount = CategoryImplementation.size();
6243
6244 // For each implemented class, write out all its meta data.
6245 for (int i = 0; i < ClsDefCount; i++)
6246 RewriteObjCClassMetaData(ClassImplementation[i], Result);
6247
6248 // For each implemented category, write out all its meta data.
6249 for (int i = 0; i < CatDefCount; i++)
6250 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
6251
Fariborz Jahaniandf795672012-02-17 00:06:14 +00006252 if (ClsDefCount > 0) {
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00006253 if (LangOpts.MicrosoftExt)
6254 Result += "__declspec(allocate(\".objc_classlist$B\")) ";
Fariborz Jahaniandf795672012-02-17 00:06:14 +00006255 Result += "static struct _class_t *L_OBJC_LABEL_CLASS_$ [";
6256 Result += llvm::utostr(ClsDefCount); Result += "]";
6257 Result +=
6258 " __attribute__((used, section (\"__DATA, __objc_classlist,"
6259 "regular,no_dead_strip\")))= {\n";
6260 for (int i = 0; i < ClsDefCount; i++) {
6261 Result += "\t&OBJC_CLASS_$_";
6262 Result += ClassImplementation[i]->getNameAsString();
6263 Result += ",\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006264 }
Fariborz Jahaniandf795672012-02-17 00:06:14 +00006265 Result += "};\n";
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006266
6267 if (!DefinedNonLazyClasses.empty()) {
6268 if (LangOpts.MicrosoftExt)
6269 Result += "__declspec(allocate(\".objc_nlclslist$B\")) \n";
6270 Result += "static struct _class_t *_OBJC_LABEL_NONLAZY_CLASS_$[] = {\n\t";
6271 for (unsigned i = 0, e = DefinedNonLazyClasses.size(); i < e; i++) {
6272 Result += "\t&OBJC_CLASS_$_"; Result += DefinedNonLazyClasses[i]->getNameAsString();
6273 Result += ",\n";
6274 }
6275 Result += "};\n";
6276 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006277 }
Fariborz Jahanian61186122012-02-17 18:40:41 +00006278
6279 if (CatDefCount > 0) {
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00006280 if (LangOpts.MicrosoftExt)
6281 Result += "__declspec(allocate(\".objc_catlist$B\")) ";
Fariborz Jahanian61186122012-02-17 18:40:41 +00006282 Result += "static struct _category_t *L_OBJC_LABEL_CATEGORY_$ [";
6283 Result += llvm::utostr(CatDefCount); Result += "]";
6284 Result +=
6285 " __attribute__((used, section (\"__DATA, __objc_catlist,"
6286 "regular,no_dead_strip\")))= {\n";
6287 for (int i = 0; i < CatDefCount; i++) {
6288 Result += "\t&_OBJC_$_CATEGORY_";
6289 Result +=
6290 CategoryImplementation[i]->getClassInterface()->getNameAsString();
6291 Result += "_$_";
6292 Result += CategoryImplementation[i]->getNameAsString();
6293 Result += ",\n";
6294 }
6295 Result += "};\n";
6296 }
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006297
6298 if (!DefinedNonLazyCategories.empty()) {
6299 if (LangOpts.MicrosoftExt)
6300 Result += "__declspec(allocate(\".objc_nlcatlist$B\")) \n";
6301 Result += "static struct _category_t *_OBJC_LABEL_NONLAZY_CATEGORY_$[] = {\n\t";
6302 for (unsigned i = 0, e = DefinedNonLazyCategories.size(); i < e; i++) {
6303 Result += "\t&_OBJC_$_CATEGORY_";
6304 Result +=
6305 DefinedNonLazyCategories[i]->getClassInterface()->getNameAsString();
6306 Result += "_$_";
6307 Result += DefinedNonLazyCategories[i]->getNameAsString();
6308 Result += ",\n";
6309 }
6310 Result += "};\n";
6311 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006312}
6313
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00006314void RewriteModernObjC::WriteImageInfo(std::string &Result) {
6315 if (LangOpts.MicrosoftExt)
6316 Result += "__declspec(allocate(\".objc_imageinfo$B\")) \n";
6317
6318 Result += "static struct IMAGE_INFO { unsigned version; unsigned flag; } ";
6319 // version 0, ObjCABI is 2
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006320 Result += "L_OBJC_IMAGE_INFO = { 0, 2 };\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00006321}
6322
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006323/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
6324/// implementation.
6325void RewriteModernObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
6326 std::string &Result) {
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00006327 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006328 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
6329 // Find category declaration for this implementation.
Fariborz Jahanian61186122012-02-17 18:40:41 +00006330 ObjCCategoryDecl *CDecl=0;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006331 for (CDecl = ClassDecl->getCategoryList(); CDecl;
6332 CDecl = CDecl->getNextClassCategory())
6333 if (CDecl->getIdentifier() == IDecl->getIdentifier())
6334 break;
6335
6336 std::string FullCategoryName = ClassDecl->getNameAsString();
Fariborz Jahanian61186122012-02-17 18:40:41 +00006337 FullCategoryName += "_$_";
6338 FullCategoryName += CDecl->getNameAsString();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006339
6340 // Build _objc_method_list for class's instance methods if needed
6341 SmallVector<ObjCMethodDecl *, 32>
6342 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
6343
6344 // If any of our property implementations have associated getters or
6345 // setters, produce metadata for them as well.
6346 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
6347 PropEnd = IDecl->propimpl_end();
6348 Prop != PropEnd; ++Prop) {
6349 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
6350 continue;
6351 if (!(*Prop)->getPropertyIvarDecl())
6352 continue;
6353 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
6354 if (!PD)
6355 continue;
6356 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
6357 InstanceMethods.push_back(Getter);
6358 if (PD->isReadOnly())
6359 continue;
6360 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
6361 InstanceMethods.push_back(Setter);
6362 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006363
Fariborz Jahanian61186122012-02-17 18:40:41 +00006364 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
6365 "_OBJC_$_CATEGORY_INSTANCE_METHODS_",
6366 FullCategoryName, true);
6367
6368 SmallVector<ObjCMethodDecl *, 32>
6369 ClassMethods(IDecl->classmeth_begin(), IDecl->classmeth_end());
6370
6371 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
6372 "_OBJC_$_CATEGORY_CLASS_METHODS_",
6373 FullCategoryName, true);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006374
6375 // Protocols referenced in class declaration?
Fariborz Jahanian61186122012-02-17 18:40:41 +00006376 // Protocol's super protocol list
6377 std::vector<ObjCProtocolDecl *> RefedProtocols;
Argyrios Kyrtzidisa5f44412012-03-13 01:09:41 +00006378 for (ObjCInterfaceDecl::protocol_iterator I = CDecl->protocol_begin(),
6379 E = CDecl->protocol_end();
6380
6381 I != E; ++I) {
Fariborz Jahanian61186122012-02-17 18:40:41 +00006382 RefedProtocols.push_back(*I);
6383 // Must write out all protocol definitions in current qualifier list,
6384 // and in their nested qualifiers before writing out current definition.
6385 RewriteObjCProtocolMetaData(*I, Result);
6386 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006387
Fariborz Jahanian61186122012-02-17 18:40:41 +00006388 Write_protocol_list_initializer(Context, Result,
6389 RefedProtocols,
6390 "_OBJC_CATEGORY_PROTOCOLS_$_",
6391 FullCategoryName);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006392
Fariborz Jahanian61186122012-02-17 18:40:41 +00006393 // Protocol's property metadata.
6394 std::vector<ObjCPropertyDecl *> ClassProperties;
6395 for (ObjCContainerDecl::prop_iterator I = CDecl->prop_begin(),
6396 E = CDecl->prop_end(); I != E; ++I)
6397 ClassProperties.push_back(*I);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006398
Fariborz Jahanian61186122012-02-17 18:40:41 +00006399 Write_prop_list_t_initializer(*this, Context, Result, ClassProperties,
6400 /* Container */0,
6401 "_OBJC_$_PROP_LIST_",
6402 FullCategoryName);
6403
6404 Write_category_t(*this, Context, Result,
6405 CDecl->getNameAsString(),
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006406 ClassDecl,
Fariborz Jahanian61186122012-02-17 18:40:41 +00006407 InstanceMethods,
6408 ClassMethods,
6409 RefedProtocols,
6410 ClassProperties);
6411
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006412 // Determine if this category is also "non-lazy".
6413 if (ImplementationIsNonLazy(IDecl))
6414 DefinedNonLazyCategories.push_back(CDecl);
6415
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006416}
6417
6418// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
6419/// class methods.
6420template<typename MethodIterator>
6421void RewriteModernObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
6422 MethodIterator MethodEnd,
6423 bool IsInstanceMethod,
6424 StringRef prefix,
6425 StringRef ClassName,
6426 std::string &Result) {
6427 if (MethodBegin == MethodEnd) return;
6428
6429 if (!objc_impl_method) {
6430 /* struct _objc_method {
6431 SEL _cmd;
6432 char *method_types;
6433 void *_imp;
6434 }
6435 */
6436 Result += "\nstruct _objc_method {\n";
6437 Result += "\tSEL _cmd;\n";
6438 Result += "\tchar *method_types;\n";
6439 Result += "\tvoid *_imp;\n";
6440 Result += "};\n";
6441
6442 objc_impl_method = true;
6443 }
6444
6445 // Build _objc_method_list for class's methods if needed
6446
6447 /* struct {
6448 struct _objc_method_list *next_method;
6449 int method_count;
6450 struct _objc_method method_list[];
6451 }
6452 */
6453 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00006454 Result += "\n";
6455 if (LangOpts.MicrosoftExt) {
6456 if (IsInstanceMethod)
6457 Result += "__declspec(allocate(\".inst_meth$B\")) ";
6458 else
6459 Result += "__declspec(allocate(\".cls_meth$B\")) ";
6460 }
6461 Result += "static struct {\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006462 Result += "\tstruct _objc_method_list *next_method;\n";
6463 Result += "\tint method_count;\n";
6464 Result += "\tstruct _objc_method method_list[";
6465 Result += utostr(NumMethods);
6466 Result += "];\n} _OBJC_";
6467 Result += prefix;
6468 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
6469 Result += "_METHODS_";
6470 Result += ClassName;
6471 Result += " __attribute__ ((used, section (\"__OBJC, __";
6472 Result += IsInstanceMethod ? "inst" : "cls";
6473 Result += "_meth\")))= ";
6474 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
6475
6476 Result += "\t,{{(SEL)\"";
6477 Result += (*MethodBegin)->getSelector().getAsString().c_str();
6478 std::string MethodTypeString;
6479 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
6480 Result += "\", \"";
6481 Result += MethodTypeString;
6482 Result += "\", (void *)";
6483 Result += MethodInternalNames[*MethodBegin];
6484 Result += "}\n";
6485 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
6486 Result += "\t ,{(SEL)\"";
6487 Result += (*MethodBegin)->getSelector().getAsString().c_str();
6488 std::string MethodTypeString;
6489 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
6490 Result += "\", \"";
6491 Result += MethodTypeString;
6492 Result += "\", (void *)";
6493 Result += MethodInternalNames[*MethodBegin];
6494 Result += "}\n";
6495 }
6496 Result += "\t }\n};\n";
6497}
6498
6499Stmt *RewriteModernObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) {
6500 SourceRange OldRange = IV->getSourceRange();
6501 Expr *BaseExpr = IV->getBase();
6502
6503 // Rewrite the base, but without actually doing replaces.
6504 {
6505 DisableReplaceStmtScope S(*this);
6506 BaseExpr = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(BaseExpr));
6507 IV->setBase(BaseExpr);
6508 }
6509
6510 ObjCIvarDecl *D = IV->getDecl();
6511
6512 Expr *Replacement = IV;
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00006513
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006514 if (BaseExpr->getType()->isObjCObjectPointerType()) {
6515 const ObjCInterfaceType *iFaceDecl =
6516 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
6517 assert(iFaceDecl && "RewriteObjCIvarRefExpr - iFaceDecl is null");
6518 // lookup which class implements the instance variable.
6519 ObjCInterfaceDecl *clsDeclared = 0;
6520 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
6521 clsDeclared);
6522 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
6523
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00006524 // Build name of symbol holding ivar offset.
6525 std::string IvarOffsetName = "OBJC_IVAR_$_";
6526 IvarOffsetName += clsDeclared->getIdentifier()->getName();
6527 IvarOffsetName += "_";
6528 IvarOffsetName += D->getName();
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00006529 ReferencedIvars[clsDeclared].insert(D);
6530
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00006531 // cast offset to "char *".
6532 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context,
6533 Context->getPointerType(Context->CharTy),
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006534 CK_BitCast,
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00006535 BaseExpr);
6536 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
6537 SourceLocation(), &Context->Idents.get(IvarOffsetName),
6538 Context->UnsignedLongTy, 0, SC_Extern, SC_None);
John McCallf4b88a42012-03-10 09:33:50 +00006539 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, false,
6540 Context->UnsignedLongTy, VK_LValue,
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00006541 SourceLocation());
6542 BinaryOperator *addExpr =
6543 new (Context) BinaryOperator(castExpr, DRE, BO_Add,
6544 Context->getPointerType(Context->CharTy),
6545 VK_RValue, OK_Ordinary, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006546 // Don't forget the parens to enforce the proper binding.
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00006547 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(),
6548 SourceLocation(),
6549 addExpr);
Fariborz Jahanian0d6e22a2012-02-24 17:35:35 +00006550 QualType IvarT = D->getType();
Fariborz Jahanian8e0913d2012-02-29 00:26:20 +00006551 convertObjCTypeToCStyleType(IvarT);
Fariborz Jahanian0d6e22a2012-02-24 17:35:35 +00006552 QualType castT = Context->getPointerType(IvarT);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006553
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00006554 castExpr = NoTypeInfoCStyleCastExpr(Context,
6555 castT,
6556 CK_BitCast,
6557 PE);
Fariborz Jahanian8e0913d2012-02-29 00:26:20 +00006558 Expr *Exp = new (Context) UnaryOperator(castExpr, UO_Deref, IvarT,
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00006559 VK_LValue, OK_Ordinary,
6560 SourceLocation());
6561 PE = new (Context) ParenExpr(OldRange.getBegin(),
6562 OldRange.getEnd(),
6563 Exp);
6564
6565 Replacement = PE;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006566 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006567
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00006568 ReplaceStmtWithRange(IV, Replacement, OldRange);
6569 return Replacement;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006570}
6571