1 //===--- CodeGenModule.h - Per-Module state for LLVM CodeGen ----*- C++ -*-===// 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 // This is the internal per-translation-unit state used for llvm translation. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #ifndef CLANG_CODEGEN_CODEGENMODULE_H 15 #define CLANG_CODEGEN_CODEGENMODULE_H 16 17 #include "clang/Basic/ABI.h" 18 #include "clang/Basic/LangOptions.h" 19 #include "clang/AST/Attr.h" 20 #include "clang/AST/DeclCXX.h" 21 #include "clang/AST/DeclObjC.h" 22 #include "clang/AST/GlobalDecl.h" 23 #include "clang/AST/Mangle.h" 24 #include "CGVTables.h" 25 #include "CodeGenTypes.h" 26 #include "llvm/Module.h" 27 #include "llvm/ADT/DenseMap.h" 28 #include "llvm/ADT/StringMap.h" 29 #include "llvm/ADT/SmallPtrSet.h" 30 #include "llvm/Support/ValueHandle.h" 31 32 namespace llvm { 33 class Module; 34 class Constant; 35 class ConstantInt; 36 class Function; 37 class GlobalValue; 38 class TargetData; 39 class FunctionType; 40 class LLVMContext; 41 } 42 43 namespace clang { 44 class TargetCodeGenInfo; 45 class ASTContext; 46 class FunctionDecl; 47 class IdentifierInfo; 48 class ObjCMethodDecl; 49 class ObjCImplementationDecl; 50 class ObjCCategoryImplDecl; 51 class ObjCProtocolDecl; 52 class ObjCEncodeExpr; 53 class BlockExpr; 54 class CharUnits; 55 class Decl; 56 class Expr; 57 class Stmt; 58 class StringLiteral; 59 class NamedDecl; 60 class ValueDecl; 61 class VarDecl; 62 class LangOptions; 63 class CodeGenOptions; 64 class DiagnosticsEngine; 65 class AnnotateAttr; 66 class CXXDestructorDecl; 67 class MangleBuffer; 68 69 namespace CodeGen { 70 71 class CallArgList; 72 class CodeGenFunction; 73 class CodeGenTBAA; 74 class CGCXXABI; 75 class CGDebugInfo; 76 class CGObjCRuntime; 77 class CGOpenCLRuntime; 78 class CGCUDARuntime; 79 class BlockFieldFlags; 80 class FunctionArgList; 81 82 struct OrderGlobalInits { 83 unsigned int priority; 84 unsigned int lex_order; 85 OrderGlobalInits(unsigned int p, unsigned int l) 86 : priority(p), lex_order(l) {} 87 88 bool operator==(const OrderGlobalInits &RHS) const { 89 return priority == RHS.priority && 90 lex_order == RHS.lex_order; 91 } 92 93 bool operator<(const OrderGlobalInits &RHS) const { 94 if (priority < RHS.priority) 95 return true; 96 97 return priority == RHS.priority && lex_order < RHS.lex_order; 98 } 99 }; 100 101 struct CodeGenTypeCache { 102 /// void 103 llvm::Type *VoidTy; 104 105 /// i8, i16, i32, and i64 106 llvm::IntegerType *Int8Ty, *Int16Ty, *Int32Ty, *Int64Ty; 107 /// float, double 108 llvm::Type *FloatTy, *DoubleTy; 109 110 /// int 111 llvm::IntegerType *IntTy; 112 113 /// intptr_t, size_t, and ptrdiff_t, which we assume are the same size. 114 union { 115 llvm::IntegerType *IntPtrTy; 116 llvm::IntegerType *SizeTy; 117 llvm::IntegerType *PtrDiffTy; 118 }; 119 120 /// void* in address space 0 121 union { 122 llvm::PointerType *VoidPtrTy; 123 llvm::PointerType *Int8PtrTy; 124 }; 125 126 /// void** in address space 0 127 union { 128 llvm::PointerType *VoidPtrPtrTy; 129 llvm::PointerType *Int8PtrPtrTy; 130 }; 131 132 /// The width of a pointer into the generic address space. 133 unsigned char PointerWidthInBits; 134 135 /// The size and alignment of a pointer into the generic address 136 /// space. 137 union { 138 unsigned char PointerAlignInBytes; 139 unsigned char PointerSizeInBytes; 140 }; 141 }; 142 143 struct RREntrypoints { 144 RREntrypoints() { memset(this, 0, sizeof(*this)); } 145 /// void objc_autoreleasePoolPop(void*); 146 llvm::Constant *objc_autoreleasePoolPop; 147 148 /// void *objc_autoreleasePoolPush(void); 149 llvm::Constant *objc_autoreleasePoolPush; 150 }; 151 152 struct ARCEntrypoints { 153 ARCEntrypoints() { memset(this, 0, sizeof(*this)); } 154 155 /// id objc_autorelease(id); 156 llvm::Constant *objc_autorelease; 157 158 /// id objc_autoreleaseReturnValue(id); 159 llvm::Constant *objc_autoreleaseReturnValue; 160 161 /// void objc_copyWeak(id *dest, id *src); 162 llvm::Constant *objc_copyWeak; 163 164 /// void objc_destroyWeak(id*); 165 llvm::Constant *objc_destroyWeak; 166 167 /// id objc_initWeak(id*, id); 168 llvm::Constant *objc_initWeak; 169 170 /// id objc_loadWeak(id*); 171 llvm::Constant *objc_loadWeak; 172 173 /// id objc_loadWeakRetained(id*); 174 llvm::Constant *objc_loadWeakRetained; 175 176 /// void objc_moveWeak(id *dest, id *src); 177 llvm::Constant *objc_moveWeak; 178 179 /// id objc_retain(id); 180 llvm::Constant *objc_retain; 181 182 /// id objc_retainAutorelease(id); 183 llvm::Constant *objc_retainAutorelease; 184 185 /// id objc_retainAutoreleaseReturnValue(id); 186 llvm::Constant *objc_retainAutoreleaseReturnValue; 187 188 /// id objc_retainAutoreleasedReturnValue(id); 189 llvm::Constant *objc_retainAutoreleasedReturnValue; 190 191 /// id objc_retainBlock(id); 192 llvm::Constant *objc_retainBlock; 193 194 /// void objc_release(id); 195 llvm::Constant *objc_release; 196 197 /// id objc_storeStrong(id*, id); 198 llvm::Constant *objc_storeStrong; 199 200 /// id objc_storeWeak(id*, id); 201 llvm::Constant *objc_storeWeak; 202 203 /// A void(void) inline asm to use to mark that the return value of 204 /// a call will be immediately retain. 205 llvm::InlineAsm *retainAutoreleasedReturnValueMarker; 206 }; 207 208 /// CodeGenModule - This class organizes the cross-function state that is used 209 /// while generating LLVM code. 210 class CodeGenModule : public CodeGenTypeCache { 211 CodeGenModule(const CodeGenModule&); // DO NOT IMPLEMENT 212 void operator=(const CodeGenModule&); // DO NOT IMPLEMENT 213 214 typedef std::vector<std::pair<llvm::Constant*, int> > CtorList; 215 216 ASTContext &Context; 217 const LangOptions &Features; 218 const CodeGenOptions &CodeGenOpts; 219 llvm::Module &TheModule; 220 const llvm::TargetData &TheTargetData; 221 mutable const TargetCodeGenInfo *TheTargetCodeGenInfo; 222 DiagnosticsEngine &Diags; 223 CGCXXABI &ABI; 224 CodeGenTypes Types; 225 CodeGenTBAA *TBAA; 226 227 /// VTables - Holds information about C++ vtables. 228 CodeGenVTables VTables; 229 friend class CodeGenVTables; 230 231 CGObjCRuntime* ObjCRuntime; 232 CGOpenCLRuntime* OpenCLRuntime; 233 CGCUDARuntime* CUDARuntime; 234 CGDebugInfo* DebugInfo; 235 ARCEntrypoints *ARCData; 236 llvm::MDNode *NoObjCARCExceptionsMetadata; 237 RREntrypoints *RRData; 238 239 // WeakRefReferences - A set of references that have only been seen via 240 // a weakref so far. This is used to remove the weak of the reference if we ever 241 // see a direct reference or a definition. 242 llvm::SmallPtrSet<llvm::GlobalValue*, 10> WeakRefReferences; 243 244 /// DeferredDecls - This contains all the decls which have definitions but 245 /// which are deferred for emission and therefore should only be output if 246 /// they are actually used. If a decl is in this, then it is known to have 247 /// not been referenced yet. 248 llvm::StringMap<GlobalDecl> DeferredDecls; 249 250 /// DeferredDeclsToEmit - This is a list of deferred decls which we have seen 251 /// that *are* actually referenced. These get code generated when the module 252 /// is done. 253 std::vector<GlobalDecl> DeferredDeclsToEmit; 254 255 /// LLVMUsed - List of global values which are required to be 256 /// present in the object file; bitcast to i8*. This is used for 257 /// forcing visibility of symbols which may otherwise be optimized 258 /// out. 259 std::vector<llvm::WeakVH> LLVMUsed; 260 261 /// GlobalCtors - Store the list of global constructors and their respective 262 /// priorities to be emitted when the translation unit is complete. 263 CtorList GlobalCtors; 264 265 /// GlobalDtors - Store the list of global destructors and their respective 266 /// priorities to be emitted when the translation unit is complete. 267 CtorList GlobalDtors; 268 269 /// MangledDeclNames - A map of canonical GlobalDecls to their mangled names. 270 llvm::DenseMap<GlobalDecl, StringRef> MangledDeclNames; 271 llvm::BumpPtrAllocator MangledNamesAllocator; 272 273 /// Global annotations. 274 std::vector<llvm::Constant*> Annotations; 275 276 /// Map used to get unique annotation strings. 277 llvm::StringMap<llvm::Constant*> AnnotationStrings; 278 279 llvm::StringMap<llvm::Constant*> CFConstantStringMap; 280 llvm::StringMap<llvm::GlobalVariable*> ConstantStringMap; 281 llvm::DenseMap<const Decl*, llvm::Value*> StaticLocalDeclMap; 282 283 llvm::DenseMap<QualType, llvm::Constant *> AtomicSetterHelperFnMap; 284 llvm::DenseMap<QualType, llvm::Constant *> AtomicGetterHelperFnMap; 285 286 /// CXXGlobalInits - Global variables with initializers that need to run 287 /// before main. 288 std::vector<llvm::Constant*> CXXGlobalInits; 289 290 /// When a C++ decl with an initializer is deferred, null is 291 /// appended to CXXGlobalInits, and the index of that null is placed 292 /// here so that the initializer will be performed in the correct 293 /// order. 294 llvm::DenseMap<const Decl*, unsigned> DelayedCXXInitPosition; 295 296 /// - Global variables with initializers whose order of initialization 297 /// is set by init_priority attribute. 298 299 SmallVector<std::pair<OrderGlobalInits, llvm::Function*>, 8> 300 PrioritizedCXXGlobalInits; 301 302 /// CXXGlobalDtors - Global destructor functions and arguments that need to 303 /// run on termination. 304 std::vector<std::pair<llvm::WeakVH,llvm::Constant*> > CXXGlobalDtors; 305 306 /// @name Cache for Objective-C runtime types 307 /// @{ 308 309 /// CFConstantStringClassRef - Cached reference to the class for constant 310 /// strings. This value has type int * but is actually an Obj-C class pointer. 311 llvm::Constant *CFConstantStringClassRef; 312 313 /// ConstantStringClassRef - Cached reference to the class for constant 314 /// strings. This value has type int * but is actually an Obj-C class pointer. 315 llvm::Constant *ConstantStringClassRef; 316 317 /// \brief The LLVM type corresponding to NSConstantString. 318 llvm::StructType *NSConstantStringType; 319 320 /// \brief The type used to describe the state of a fast enumeration in 321 /// Objective-C's for..in loop. 322 QualType ObjCFastEnumerationStateType; 323 324 /// @} 325 326 /// Lazily create the Objective-C runtime 327 void createObjCRuntime(); 328 329 void createOpenCLRuntime(); 330 void createCUDARuntime(); 331 332 bool isTriviallyRecursive(const FunctionDecl *F); 333 bool shouldEmitFunction(const FunctionDecl *F); 334 llvm::LLVMContext &VMContext; 335 336 /// @name Cache for Blocks Runtime Globals 337 /// @{ 338 339 llvm::Constant *NSConcreteGlobalBlock; 340 llvm::Constant *NSConcreteStackBlock; 341 342 llvm::Constant *BlockObjectAssign; 343 llvm::Constant *BlockObjectDispose; 344 345 llvm::Type *BlockDescriptorType; 346 llvm::Type *GenericBlockLiteralType; 347 348 struct { 349 int GlobalUniqueCount; 350 } Block; 351 352 /// @} 353 public: 354 CodeGenModule(ASTContext &C, const CodeGenOptions &CodeGenOpts, 355 llvm::Module &M, const llvm::TargetData &TD, 356 DiagnosticsEngine &Diags); 357 358 ~CodeGenModule(); 359 360 /// Release - Finalize LLVM code generation. 361 void Release(); 362 363 /// getObjCRuntime() - Return a reference to the configured 364 /// Objective-C runtime. 365 CGObjCRuntime &getObjCRuntime() { 366 if (!ObjCRuntime) createObjCRuntime(); 367 return *ObjCRuntime; 368 } 369 370 /// hasObjCRuntime() - Return true iff an Objective-C runtime has 371 /// been configured. 372 bool hasObjCRuntime() { return !!ObjCRuntime; } 373 374 /// getOpenCLRuntime() - Return a reference to the configured OpenCL runtime. 375 CGOpenCLRuntime &getOpenCLRuntime() { 376 assert(OpenCLRuntime != 0); 377 return *OpenCLRuntime; 378 } 379 380 /// getCUDARuntime() - Return a reference to the configured CUDA runtime. 381 CGCUDARuntime &getCUDARuntime() { 382 assert(CUDARuntime != 0); 383 return *CUDARuntime; 384 } 385 386 /// getCXXABI() - Return a reference to the configured C++ ABI. 387 CGCXXABI &getCXXABI() { return ABI; } 388 389 ARCEntrypoints &getARCEntrypoints() const { 390 assert(getLangOptions().ObjCAutoRefCount && ARCData != 0); 391 return *ARCData; 392 } 393 394 RREntrypoints &getRREntrypoints() const { 395 assert(RRData != 0); 396 return *RRData; 397 } 398 399 llvm::Value *getStaticLocalDeclAddress(const VarDecl *VD) { 400 return StaticLocalDeclMap[VD]; 401 } 402 void setStaticLocalDeclAddress(const VarDecl *D, 403 llvm::GlobalVariable *GV) { 404 StaticLocalDeclMap[D] = GV; 405 } 406 407 llvm::Constant *getAtomicSetterHelperFnMap(QualType Ty) { 408 return AtomicSetterHelperFnMap[Ty]; 409 } 410 void setAtomicSetterHelperFnMap(QualType Ty, 411 llvm::Constant *Fn) { 412 AtomicSetterHelperFnMap[Ty] = Fn; 413 } 414 415 llvm::Constant *getAtomicGetterHelperFnMap(QualType Ty) { 416 return AtomicGetterHelperFnMap[Ty]; 417 } 418 void setAtomicGetterHelperFnMap(QualType Ty, 419 llvm::Constant *Fn) { 420 AtomicGetterHelperFnMap[Ty] = Fn; 421 } 422 423 CGDebugInfo *getModuleDebugInfo() { return DebugInfo; } 424 425 llvm::MDNode *getNoObjCARCExceptionsMetadata() { 426 if (!NoObjCARCExceptionsMetadata) 427 NoObjCARCExceptionsMetadata = 428 llvm::MDNode::get(getLLVMContext(), 429 SmallVector<llvm::Value*,1>()); 430 return NoObjCARCExceptionsMetadata; 431 } 432 433 ASTContext &getContext() const { return Context; } 434 const CodeGenOptions &getCodeGenOpts() const { return CodeGenOpts; } 435 const LangOptions &getLangOptions() const { return Features; } 436 llvm::Module &getModule() const { return TheModule; } 437 CodeGenTypes &getTypes() { return Types; } 438 CodeGenVTables &getVTables() { return VTables; } 439 VTableContext &getVTableContext() { return VTables.getVTableContext(); } 440 DiagnosticsEngine &getDiags() const { return Diags; } 441 const llvm::TargetData &getTargetData() const { return TheTargetData; } 442 const TargetInfo &getTarget() const { return Context.getTargetInfo(); } 443 llvm::LLVMContext &getLLVMContext() { return VMContext; } 444 const TargetCodeGenInfo &getTargetCodeGenInfo(); 445 bool isTargetDarwin() const; 446 447 bool shouldUseTBAA() const { return TBAA != 0; } 448 449 llvm::MDNode *getTBAAInfo(QualType QTy); 450 451 bool isTypeConstant(QualType QTy, bool ExcludeCtorDtor); 452 453 static void DecorateInstruction(llvm::Instruction *Inst, 454 llvm::MDNode *TBAAInfo); 455 456 /// getSize - Emit the given number of characters as a value of type size_t. 457 llvm::ConstantInt *getSize(CharUnits numChars); 458 459 /// setGlobalVisibility - Set the visibility for the given LLVM 460 /// GlobalValue. 461 void setGlobalVisibility(llvm::GlobalValue *GV, const NamedDecl *D) const; 462 463 /// TypeVisibilityKind - The kind of global variable that is passed to 464 /// setTypeVisibility 465 enum TypeVisibilityKind { 466 TVK_ForVTT, 467 TVK_ForVTable, 468 TVK_ForConstructionVTable, 469 TVK_ForRTTI, 470 TVK_ForRTTIName 471 }; 472 473 /// setTypeVisibility - Set the visibility for the given global 474 /// value which holds information about a type. 475 void setTypeVisibility(llvm::GlobalValue *GV, const CXXRecordDecl *D, 476 TypeVisibilityKind TVK) const; 477 478 static llvm::GlobalValue::VisibilityTypes GetLLVMVisibility(Visibility V) { 479 switch (V) { 480 case DefaultVisibility: return llvm::GlobalValue::DefaultVisibility; 481 case HiddenVisibility: return llvm::GlobalValue::HiddenVisibility; 482 case ProtectedVisibility: return llvm::GlobalValue::ProtectedVisibility; 483 } 484 llvm_unreachable("unknown visibility!"); 485 } 486 487 llvm::Constant *GetAddrOfGlobal(GlobalDecl GD) { 488 if (isa<CXXConstructorDecl>(GD.getDecl())) 489 return GetAddrOfCXXConstructor(cast<CXXConstructorDecl>(GD.getDecl()), 490 GD.getCtorType()); 491 else if (isa<CXXDestructorDecl>(GD.getDecl())) 492 return GetAddrOfCXXDestructor(cast<CXXDestructorDecl>(GD.getDecl()), 493 GD.getDtorType()); 494 else if (isa<FunctionDecl>(GD.getDecl())) 495 return GetAddrOfFunction(GD); 496 else 497 return GetAddrOfGlobalVar(cast<VarDecl>(GD.getDecl())); 498 } 499 500 /// CreateOrReplaceCXXRuntimeVariable - Will return a global variable of the given 501 /// type. If a variable with a different type already exists then a new 502 /// variable with the right type will be created and all uses of the old 503 /// variable will be replaced with a bitcast to the new variable. 504 llvm::GlobalVariable * 505 CreateOrReplaceCXXRuntimeVariable(StringRef Name, llvm::Type *Ty, 506 llvm::GlobalValue::LinkageTypes Linkage); 507 508 /// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the 509 /// given global variable. If Ty is non-null and if the global doesn't exist, 510 /// then it will be greated with the specified type instead of whatever the 511 /// normal requested type would be. 512 llvm::Constant *GetAddrOfGlobalVar(const VarDecl *D, 513 llvm::Type *Ty = 0); 514 515 516 /// GetAddrOfFunction - Return the address of the given function. If Ty is 517 /// non-null, then this function will use the specified type if it has to 518 /// create it. 519 llvm::Constant *GetAddrOfFunction(GlobalDecl GD, 520 llvm::Type *Ty = 0, 521 bool ForVTable = false); 522 523 /// GetAddrOfRTTIDescriptor - Get the address of the RTTI descriptor 524 /// for the given type. 525 llvm::Constant *GetAddrOfRTTIDescriptor(QualType Ty, bool ForEH = false); 526 527 /// GetAddrOfThunk - Get the address of the thunk for the given global decl. 528 llvm::Constant *GetAddrOfThunk(GlobalDecl GD, const ThunkInfo &Thunk); 529 530 /// GetWeakRefReference - Get a reference to the target of VD. 531 llvm::Constant *GetWeakRefReference(const ValueDecl *VD); 532 533 /// GetNonVirtualBaseClassOffset - Returns the offset from a derived class to 534 /// a class. Returns null if the offset is 0. 535 llvm::Constant * 536 GetNonVirtualBaseClassOffset(const CXXRecordDecl *ClassDecl, 537 CastExpr::path_const_iterator PathBegin, 538 CastExpr::path_const_iterator PathEnd); 539 540 /// A pair of helper functions for a __block variable. 541 class ByrefHelpers : public llvm::FoldingSetNode { 542 public: 543 llvm::Constant *CopyHelper; 544 llvm::Constant *DisposeHelper; 545 546 /// The alignment of the field. This is important because 547 /// different offsets to the field within the byref struct need to 548 /// have different helper functions. 549 CharUnits Alignment; 550 551 ByrefHelpers(CharUnits alignment) : Alignment(alignment) {} 552 virtual ~ByrefHelpers(); 553 554 void Profile(llvm::FoldingSetNodeID &id) const { 555 id.AddInteger(Alignment.getQuantity()); 556 profileImpl(id); 557 } 558 virtual void profileImpl(llvm::FoldingSetNodeID &id) const = 0; 559 560 virtual bool needsCopy() const { return true; } 561 virtual void emitCopy(CodeGenFunction &CGF, 562 llvm::Value *dest, llvm::Value *src) = 0; 563 564 virtual bool needsDispose() const { return true; } 565 virtual void emitDispose(CodeGenFunction &CGF, llvm::Value *field) = 0; 566 }; 567 568 llvm::FoldingSet<ByrefHelpers> ByrefHelpersCache; 569 570 /// getUniqueBlockCount - Fetches the global unique block count. 571 int getUniqueBlockCount() { return ++Block.GlobalUniqueCount; } 572 573 /// getBlockDescriptorType - Fetches the type of a generic block 574 /// descriptor. 575 llvm::Type *getBlockDescriptorType(); 576 577 /// getGenericBlockLiteralType - The type of a generic block literal. 578 llvm::Type *getGenericBlockLiteralType(); 579 580 /// GetAddrOfGlobalBlock - Gets the address of a block which 581 /// requires no captures. 582 llvm::Constant *GetAddrOfGlobalBlock(const BlockExpr *BE, const char *); 583 584 /// GetAddrOfConstantCFString - Return a pointer to a constant CFString object 585 /// for the given string. 586 llvm::Constant *GetAddrOfConstantCFString(const StringLiteral *Literal); 587 588 /// GetAddrOfConstantString - Return a pointer to a constant NSString object 589 /// for the given string. Or a user defined String object as defined via 590 /// -fconstant-string-class=class_name option. 591 llvm::Constant *GetAddrOfConstantString(const StringLiteral *Literal); 592 593 /// GetConstantArrayFromStringLiteral - Return a constant array for the given 594 /// string. 595 llvm::Constant *GetConstantArrayFromStringLiteral(const StringLiteral *E); 596 597 /// GetAddrOfConstantStringFromLiteral - Return a pointer to a constant array 598 /// for the given string literal. 599 llvm::Constant *GetAddrOfConstantStringFromLiteral(const StringLiteral *S); 600 601 /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant 602 /// array for the given ObjCEncodeExpr node. 603 llvm::Constant *GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *); 604 605 /// GetAddrOfConstantString - Returns a pointer to a character array 606 /// containing the literal. This contents are exactly that of the given 607 /// string, i.e. it will not be null terminated automatically; see 608 /// GetAddrOfConstantCString. Note that whether the result is actually a 609 /// pointer to an LLVM constant depends on Feature.WriteableStrings. 610 /// 611 /// The result has pointer to array type. 612 /// 613 /// \param GlobalName If provided, the name to use for the global 614 /// (if one is created). 615 llvm::Constant *GetAddrOfConstantString(StringRef Str, 616 const char *GlobalName=0, 617 unsigned Alignment=1); 618 619 /// GetAddrOfConstantCString - Returns a pointer to a character array 620 /// containing the literal and a terminating '\0' character. The result has 621 /// pointer to array type. 622 /// 623 /// \param GlobalName If provided, the name to use for the global (if one is 624 /// created). 625 llvm::Constant *GetAddrOfConstantCString(const std::string &str, 626 const char *GlobalName=0, 627 unsigned Alignment=1); 628 629 /// GetAddrOfConstantCompoundLiteral - Returns a pointer to a constant global 630 /// variable for the given file-scope compound literal expression. 631 llvm::Constant *GetAddrOfConstantCompoundLiteral(const CompoundLiteralExpr*E); 632 633 /// \brief Retrieve the record type that describes the state of an 634 /// Objective-C fast enumeration loop (for..in). 635 QualType getObjCFastEnumerationStateType(); 636 637 /// GetAddrOfCXXConstructor - Return the address of the constructor of the 638 /// given type. 639 llvm::GlobalValue *GetAddrOfCXXConstructor(const CXXConstructorDecl *ctor, 640 CXXCtorType ctorType, 641 const CGFunctionInfo *fnInfo = 0); 642 643 /// GetAddrOfCXXDestructor - Return the address of the constructor of the 644 /// given type. 645 llvm::GlobalValue *GetAddrOfCXXDestructor(const CXXDestructorDecl *dtor, 646 CXXDtorType dtorType, 647 const CGFunctionInfo *fnInfo = 0); 648 649 /// getBuiltinLibFunction - Given a builtin id for a function like 650 /// "__builtin_fabsf", return a Function* for "fabsf". 651 llvm::Value *getBuiltinLibFunction(const FunctionDecl *FD, 652 unsigned BuiltinID); 653 654 llvm::Function *getIntrinsic(unsigned IID, ArrayRef<llvm::Type*> Tys = 655 ArrayRef<llvm::Type*>()); 656 657 /// EmitTopLevelDecl - Emit code for a single top level declaration. 658 void EmitTopLevelDecl(Decl *D); 659 660 /// AddUsedGlobal - Add a global which should be forced to be 661 /// present in the object file; these are emitted to the llvm.used 662 /// metadata global. 663 void AddUsedGlobal(llvm::GlobalValue *GV); 664 665 /// AddCXXDtorEntry - Add a destructor and object to add to the C++ global 666 /// destructor function. 667 void AddCXXDtorEntry(llvm::Constant *DtorFn, llvm::Constant *Object) { 668 CXXGlobalDtors.push_back(std::make_pair(DtorFn, Object)); 669 } 670 671 /// CreateRuntimeFunction - Create a new runtime function with the specified 672 /// type and name. 673 llvm::Constant *CreateRuntimeFunction(llvm::FunctionType *Ty, 674 StringRef Name, 675 llvm::Attributes ExtraAttrs = 676 llvm::Attribute::None); 677 /// CreateRuntimeVariable - Create a new runtime global variable with the 678 /// specified type and name. 679 llvm::Constant *CreateRuntimeVariable(llvm::Type *Ty, 680 StringRef Name); 681 682 ///@name Custom Blocks Runtime Interfaces 683 ///@{ 684 685 llvm::Constant *getNSConcreteGlobalBlock(); 686 llvm::Constant *getNSConcreteStackBlock(); 687 llvm::Constant *getBlockObjectAssign(); 688 llvm::Constant *getBlockObjectDispose(); 689 690 ///@} 691 692 // UpdateCompleteType - Make sure that this type is translated. 693 void UpdateCompletedType(const TagDecl *TD); 694 695 llvm::Constant *getMemberPointerConstant(const UnaryOperator *e); 696 697 /// EmitConstantInit - Try to emit the initializer for the given declaration 698 /// as a constant; returns 0 if the expression cannot be emitted as a 699 /// constant. 700 llvm::Constant *EmitConstantInit(const VarDecl &D, CodeGenFunction *CGF = 0); 701 702 /// EmitConstantExpr - Try to emit the given expression as a 703 /// constant; returns 0 if the expression cannot be emitted as a 704 /// constant. 705 llvm::Constant *EmitConstantExpr(const Expr *E, QualType DestType, 706 CodeGenFunction *CGF = 0); 707 708 /// EmitConstantValue - Try to emit the given constant value as a 709 /// constant; returns 0 if the value cannot be emitted as a constant. 710 llvm::Constant *EmitConstantValue(const APValue &Value, QualType DestType, 711 CodeGenFunction *CGF = 0); 712 713 /// EmitNullConstant - Return the result of value-initializing the given 714 /// type, i.e. a null expression of the given type. This is usually, 715 /// but not always, an LLVM null constant. 716 llvm::Constant *EmitNullConstant(QualType T); 717 718 /// EmitNullConstantForBase - Return a null constant appropriate for 719 /// zero-initializing a base class with the given type. This is usually, 720 /// but not always, an LLVM null constant. 721 llvm::Constant *EmitNullConstantForBase(const CXXRecordDecl *Record); 722 723 /// Error - Emit a general error that something can't be done. 724 void Error(SourceLocation loc, StringRef error); 725 726 /// ErrorUnsupported - Print out an error that codegen doesn't support the 727 /// specified stmt yet. 728 /// \param OmitOnError - If true, then this error should only be emitted if no 729 /// other errors have been reported. 730 void ErrorUnsupported(const Stmt *S, const char *Type, 731 bool OmitOnError=false); 732 733 /// ErrorUnsupported - Print out an error that codegen doesn't support the 734 /// specified decl yet. 735 /// \param OmitOnError - If true, then this error should only be emitted if no 736 /// other errors have been reported. 737 void ErrorUnsupported(const Decl *D, const char *Type, 738 bool OmitOnError=false); 739 740 /// SetInternalFunctionAttributes - Set the attributes on the LLVM 741 /// function for the given decl and function info. This applies 742 /// attributes necessary for handling the ABI as well as user 743 /// specified attributes like section. 744 void SetInternalFunctionAttributes(const Decl *D, llvm::Function *F, 745 const CGFunctionInfo &FI); 746 747 /// SetLLVMFunctionAttributes - Set the LLVM function attributes 748 /// (sext, zext, etc). 749 void SetLLVMFunctionAttributes(const Decl *D, 750 const CGFunctionInfo &Info, 751 llvm::Function *F); 752 753 /// SetLLVMFunctionAttributesForDefinition - Set the LLVM function attributes 754 /// which only apply to a function definintion. 755 void SetLLVMFunctionAttributesForDefinition(const Decl *D, llvm::Function *F); 756 757 /// ReturnTypeUsesSRet - Return true iff the given type uses 'sret' when used 758 /// as a return type. 759 bool ReturnTypeUsesSRet(const CGFunctionInfo &FI); 760 761 /// ReturnTypeUsesFPRet - Return true iff the given type uses 'fpret' when 762 /// used as a return type. 763 bool ReturnTypeUsesFPRet(QualType ResultType); 764 765 /// ReturnTypeUsesFP2Ret - Return true iff the given type uses 'fp2ret' when 766 /// used as a return type. 767 bool ReturnTypeUsesFP2Ret(QualType ResultType); 768 769 /// ConstructAttributeList - Get the LLVM attributes and calling convention to 770 /// use for a particular function type. 771 /// 772 /// \param Info - The function type information. 773 /// \param TargetDecl - The decl these attributes are being constructed 774 /// for. If supplied the attributes applied to this decl may contribute to the 775 /// function attributes and calling convention. 776 /// \param PAL [out] - On return, the attribute list to use. 777 /// \param CallingConv [out] - On return, the LLVM calling convention to use. 778 void ConstructAttributeList(const CGFunctionInfo &Info, 779 const Decl *TargetDecl, 780 AttributeListType &PAL, 781 unsigned &CallingConv); 782 783 StringRef getMangledName(GlobalDecl GD); 784 void getBlockMangledName(GlobalDecl GD, MangleBuffer &Buffer, 785 const BlockDecl *BD); 786 787 void EmitTentativeDefinition(const VarDecl *D); 788 789 void EmitVTable(CXXRecordDecl *Class, bool DefinitionRequired); 790 791 llvm::GlobalVariable::LinkageTypes 792 getFunctionLinkage(const FunctionDecl *FD); 793 794 void setFunctionLinkage(const FunctionDecl *FD, llvm::GlobalValue *V) { 795 V->setLinkage(getFunctionLinkage(FD)); 796 } 797 798 /// getVTableLinkage - Return the appropriate linkage for the vtable, VTT, 799 /// and type information of the given class. 800 llvm::GlobalVariable::LinkageTypes getVTableLinkage(const CXXRecordDecl *RD); 801 802 /// GetTargetTypeStoreSize - Return the store size, in character units, of 803 /// the given LLVM type. 804 CharUnits GetTargetTypeStoreSize(llvm::Type *Ty) const; 805 806 /// GetLLVMLinkageVarDefinition - Returns LLVM linkage for a global 807 /// variable. 808 llvm::GlobalValue::LinkageTypes 809 GetLLVMLinkageVarDefinition(const VarDecl *D, 810 llvm::GlobalVariable *GV); 811 812 std::vector<const CXXRecordDecl*> DeferredVTables; 813 814 /// Emit all the global annotations. 815 void EmitGlobalAnnotations(); 816 817 /// Emit an annotation string. 818 llvm::Constant *EmitAnnotationString(llvm::StringRef Str); 819 820 /// Emit the annotation's translation unit. 821 llvm::Constant *EmitAnnotationUnit(SourceLocation Loc); 822 823 /// Emit the annotation line number. 824 llvm::Constant *EmitAnnotationLineNo(SourceLocation L); 825 826 /// EmitAnnotateAttr - Generate the llvm::ConstantStruct which contains the 827 /// annotation information for a given GlobalValue. The annotation struct is 828 /// {i8 *, i8 *, i8 *, i32}. The first field is a constant expression, the 829 /// GlobalValue being annotated. The second field is the constant string 830 /// created from the AnnotateAttr's annotation. The third field is a constant 831 /// string containing the name of the translation unit. The fourth field is 832 /// the line number in the file of the annotated value declaration. 833 llvm::Constant *EmitAnnotateAttr(llvm::GlobalValue *GV, 834 const AnnotateAttr *AA, 835 SourceLocation L); 836 837 /// Add global annotations that are set on D, for the global GV. Those 838 /// annotations are emitted during finalization of the LLVM code. 839 void AddGlobalAnnotations(const ValueDecl *D, llvm::GlobalValue *GV); 840 841 private: 842 llvm::GlobalValue *GetGlobalValue(StringRef Ref); 843 844 llvm::Constant *GetOrCreateLLVMFunction(StringRef MangledName, 845 llvm::Type *Ty, 846 GlobalDecl D, 847 bool ForVTable, 848 llvm::Attributes ExtraAttrs = 849 llvm::Attribute::None); 850 llvm::Constant *GetOrCreateLLVMGlobal(StringRef MangledName, 851 llvm::PointerType *PTy, 852 const VarDecl *D, 853 bool UnnamedAddr = false); 854 855 /// SetCommonAttributes - Set attributes which are common to any 856 /// form of a global definition (alias, Objective-C method, 857 /// function, global variable). 858 /// 859 /// NOTE: This should only be called for definitions. 860 void SetCommonAttributes(const Decl *D, llvm::GlobalValue *GV); 861 862 /// SetFunctionDefinitionAttributes - Set attributes for a global definition. 863 void SetFunctionDefinitionAttributes(const FunctionDecl *D, 864 llvm::GlobalValue *GV); 865 866 /// SetFunctionAttributes - Set function attributes for a function 867 /// declaration. 868 void SetFunctionAttributes(GlobalDecl GD, 869 llvm::Function *F, 870 bool IsIncompleteFunction); 871 872 /// EmitGlobal - Emit code for a singal global function or var decl. Forward 873 /// declarations are emitted lazily. 874 void EmitGlobal(GlobalDecl D); 875 876 void EmitGlobalDefinition(GlobalDecl D); 877 878 void EmitGlobalFunctionDefinition(GlobalDecl GD); 879 void EmitGlobalVarDefinition(const VarDecl *D); 880 void EmitAliasDefinition(GlobalDecl GD); 881 void EmitObjCPropertyImplementations(const ObjCImplementationDecl *D); 882 void EmitObjCIvarInitializations(ObjCImplementationDecl *D); 883 884 // C++ related functions. 885 886 bool TryEmitDefinitionAsAlias(GlobalDecl Alias, GlobalDecl Target); 887 bool TryEmitBaseDestructorAsAlias(const CXXDestructorDecl *D); 888 889 void EmitNamespace(const NamespaceDecl *D); 890 void EmitLinkageSpec(const LinkageSpecDecl *D); 891 892 /// EmitCXXConstructors - Emit constructors (base, complete) from a 893 /// C++ constructor Decl. 894 void EmitCXXConstructors(const CXXConstructorDecl *D); 895 896 /// EmitCXXConstructor - Emit a single constructor with the given type from 897 /// a C++ constructor Decl. 898 void EmitCXXConstructor(const CXXConstructorDecl *D, CXXCtorType Type); 899 900 /// EmitCXXDestructors - Emit destructors (base, complete) from a 901 /// C++ destructor Decl. 902 void EmitCXXDestructors(const CXXDestructorDecl *D); 903 904 /// EmitCXXDestructor - Emit a single destructor with the given type from 905 /// a C++ destructor Decl. 906 void EmitCXXDestructor(const CXXDestructorDecl *D, CXXDtorType Type); 907 908 /// EmitCXXGlobalInitFunc - Emit the function that initializes C++ globals. 909 void EmitCXXGlobalInitFunc(); 910 911 /// EmitCXXGlobalDtorFunc - Emit the function that destroys C++ globals. 912 void EmitCXXGlobalDtorFunc(); 913 914 /// EmitCXXGlobalVarDeclInitFunc - Emit the function that initializes the 915 /// specified global (if PerformInit is true) and registers its destructor. 916 void EmitCXXGlobalVarDeclInitFunc(const VarDecl *D, 917 llvm::GlobalVariable *Addr, 918 bool PerformInit); 919 920 // FIXME: Hardcoding priority here is gross. 921 void AddGlobalCtor(llvm::Function *Ctor, int Priority=65535); 922 void AddGlobalDtor(llvm::Function *Dtor, int Priority=65535); 923 924 /// EmitCtorList - Generates a global array of functions and priorities using 925 /// the given list and name. This array will have appending linkage and is 926 /// suitable for use as a LLVM constructor or destructor array. 927 void EmitCtorList(const CtorList &Fns, const char *GlobalName); 928 929 /// EmitFundamentalRTTIDescriptor - Emit the RTTI descriptors for the 930 /// given type. 931 void EmitFundamentalRTTIDescriptor(QualType Type); 932 933 /// EmitFundamentalRTTIDescriptors - Emit the RTTI descriptors for the 934 /// builtin types. 935 void EmitFundamentalRTTIDescriptors(); 936 937 /// EmitDeferred - Emit any needed decls for which code generation 938 /// was deferred. 939 void EmitDeferred(void); 940 941 /// EmitLLVMUsed - Emit the llvm.used metadata used to force 942 /// references to global which may otherwise be optimized out. 943 void EmitLLVMUsed(void); 944 945 void EmitDeclMetadata(); 946 947 /// EmitCoverageFile - Emit the llvm.gcov metadata used to tell LLVM where 948 /// to emit the .gcno and .gcda files in a way that persists in .bc files. 949 void EmitCoverageFile(); 950 951 /// MayDeferGeneration - Determine if the given decl can be emitted 952 /// lazily; this is only relevant for definitions. The given decl 953 /// must be either a function or var decl. 954 bool MayDeferGeneration(const ValueDecl *D); 955 956 /// SimplifyPersonality - Check whether we can use a "simpler", more 957 /// core exceptions personality function. 958 void SimplifyPersonality(); 959 }; 960 } // end namespace CodeGen 961 } // end namespace clang 962 963 #endif 964