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