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