1 //===--- CodeGenModule.cpp - Emit LLVM Code from ASTs for a Module --------===//
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 coordinates the per-module state used while generating code.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "CodeGenModule.h"
15 #include "CGCUDARuntime.h"
16 #include "CGCXXABI.h"
17 #include "CGCall.h"
18 #include "CGDebugInfo.h"
19 #include "CGObjCRuntime.h"
20 #include "CGOpenCLRuntime.h"
21 #include "CodeGenFunction.h"
22 #include "CodeGenTBAA.h"
23 #include "TargetInfo.h"
24 #include "clang/AST/ASTContext.h"
25 #include "clang/AST/CharUnits.h"
26 #include "clang/AST/DeclCXX.h"
27 #include "clang/AST/DeclObjC.h"
28 #include "clang/AST/DeclTemplate.h"
29 #include "clang/AST/Mangle.h"
30 #include "clang/AST/RecordLayout.h"
31 #include "clang/AST/RecursiveASTVisitor.h"
32 #include "clang/Basic/Builtins.h"
33 #include "clang/Basic/CharInfo.h"
34 #include "clang/Basic/Diagnostic.h"
35 #include "clang/Basic/Module.h"
36 #include "clang/Basic/SourceManager.h"
37 #include "clang/Basic/TargetInfo.h"
38 #include "clang/Frontend/CodeGenOptions.h"
39 #include "llvm/ADT/APSInt.h"
40 #include "llvm/ADT/Triple.h"
41 #include "llvm/IR/CallingConv.h"
42 #include "llvm/IR/DataLayout.h"
43 #include "llvm/IR/Intrinsics.h"
44 #include "llvm/IR/LLVMContext.h"
45 #include "llvm/IR/Module.h"
46 #include "llvm/Support/CallSite.h"
47 #include "llvm/Support/ConvertUTF.h"
48 #include "llvm/Support/ErrorHandling.h"
49 #include "llvm/Target/Mangler.h"
50
51 using namespace clang;
52 using namespace CodeGen;
53
54 static const char AnnotationSection[] = "llvm.metadata";
55
createCXXABI(CodeGenModule & CGM)56 static CGCXXABI &createCXXABI(CodeGenModule &CGM) {
57 switch (CGM.getTarget().getCXXABI().getKind()) {
58 case TargetCXXABI::GenericAArch64:
59 case TargetCXXABI::GenericARM:
60 case TargetCXXABI::iOS:
61 case TargetCXXABI::GenericItanium:
62 return *CreateItaniumCXXABI(CGM);
63 case TargetCXXABI::Microsoft:
64 return *CreateMicrosoftCXXABI(CGM);
65 }
66
67 llvm_unreachable("invalid C++ ABI kind");
68 }
69
70
CodeGenModule(ASTContext & C,const CodeGenOptions & CGO,llvm::Module & M,const llvm::DataLayout & TD,DiagnosticsEngine & diags)71 CodeGenModule::CodeGenModule(ASTContext &C, const CodeGenOptions &CGO,
72 llvm::Module &M, const llvm::DataLayout &TD,
73 DiagnosticsEngine &diags)
74 : Context(C), LangOpts(C.getLangOpts()), CodeGenOpts(CGO), TheModule(M),
75 Diags(diags), TheDataLayout(TD), Target(C.getTargetInfo()),
76 ABI(createCXXABI(*this)), VMContext(M.getContext()), TBAA(0),
77 TheTargetCodeGenInfo(0), Types(*this), VTables(*this),
78 ObjCRuntime(0), OpenCLRuntime(0), CUDARuntime(0),
79 DebugInfo(0), ARCData(0), NoObjCARCExceptionsMetadata(0),
80 RRData(0), CFConstantStringClassRef(0),
81 ConstantStringClassRef(0), NSConstantStringType(0),
82 NSConcreteGlobalBlock(0), NSConcreteStackBlock(0),
83 BlockObjectAssign(0), BlockObjectDispose(0),
84 BlockDescriptorType(0), GenericBlockLiteralType(0),
85 LifetimeStartFn(0), LifetimeEndFn(0),
86 SanitizerBlacklist(CGO.SanitizerBlacklistFile),
87 SanOpts(SanitizerBlacklist.isIn(M) ?
88 SanitizerOptions::Disabled : LangOpts.Sanitize) {
89
90 // Initialize the type cache.
91 llvm::LLVMContext &LLVMContext = M.getContext();
92 VoidTy = llvm::Type::getVoidTy(LLVMContext);
93 Int8Ty = llvm::Type::getInt8Ty(LLVMContext);
94 Int16Ty = llvm::Type::getInt16Ty(LLVMContext);
95 Int32Ty = llvm::Type::getInt32Ty(LLVMContext);
96 Int64Ty = llvm::Type::getInt64Ty(LLVMContext);
97 FloatTy = llvm::Type::getFloatTy(LLVMContext);
98 DoubleTy = llvm::Type::getDoubleTy(LLVMContext);
99 PointerWidthInBits = C.getTargetInfo().getPointerWidth(0);
100 PointerAlignInBytes =
101 C.toCharUnitsFromBits(C.getTargetInfo().getPointerAlign(0)).getQuantity();
102 IntTy = llvm::IntegerType::get(LLVMContext, C.getTargetInfo().getIntWidth());
103 IntPtrTy = llvm::IntegerType::get(LLVMContext, PointerWidthInBits);
104 Int8PtrTy = Int8Ty->getPointerTo(0);
105 Int8PtrPtrTy = Int8PtrTy->getPointerTo(0);
106
107 RuntimeCC = getTargetCodeGenInfo().getABIInfo().getRuntimeCC();
108
109 if (LangOpts.ObjC1)
110 createObjCRuntime();
111 if (LangOpts.OpenCL)
112 createOpenCLRuntime();
113 if (LangOpts.CUDA)
114 createCUDARuntime();
115
116 // Enable TBAA unless it's suppressed. ThreadSanitizer needs TBAA even at O0.
117 if (SanOpts.Thread ||
118 (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0))
119 TBAA = new CodeGenTBAA(Context, VMContext, CodeGenOpts, getLangOpts(),
120 ABI.getMangleContext());
121
122 // If debug info or coverage generation is enabled, create the CGDebugInfo
123 // object.
124 if (CodeGenOpts.getDebugInfo() != CodeGenOptions::NoDebugInfo ||
125 CodeGenOpts.EmitGcovArcs ||
126 CodeGenOpts.EmitGcovNotes)
127 DebugInfo = new CGDebugInfo(*this);
128
129 Block.GlobalUniqueCount = 0;
130
131 if (C.getLangOpts().ObjCAutoRefCount)
132 ARCData = new ARCEntrypoints();
133 RRData = new RREntrypoints();
134 }
135
~CodeGenModule()136 CodeGenModule::~CodeGenModule() {
137 delete ObjCRuntime;
138 delete OpenCLRuntime;
139 delete CUDARuntime;
140 delete TheTargetCodeGenInfo;
141 delete &ABI;
142 delete TBAA;
143 delete DebugInfo;
144 delete ARCData;
145 delete RRData;
146 }
147
createObjCRuntime()148 void CodeGenModule::createObjCRuntime() {
149 // This is just isGNUFamily(), but we want to force implementors of
150 // new ABIs to decide how best to do this.
151 switch (LangOpts.ObjCRuntime.getKind()) {
152 case ObjCRuntime::GNUstep:
153 case ObjCRuntime::GCC:
154 case ObjCRuntime::ObjFW:
155 ObjCRuntime = CreateGNUObjCRuntime(*this);
156 return;
157
158 case ObjCRuntime::FragileMacOSX:
159 case ObjCRuntime::MacOSX:
160 case ObjCRuntime::iOS:
161 ObjCRuntime = CreateMacObjCRuntime(*this);
162 return;
163 }
164 llvm_unreachable("bad runtime kind");
165 }
166
createOpenCLRuntime()167 void CodeGenModule::createOpenCLRuntime() {
168 OpenCLRuntime = new CGOpenCLRuntime(*this);
169 }
170
createCUDARuntime()171 void CodeGenModule::createCUDARuntime() {
172 CUDARuntime = CreateNVCUDARuntime(*this);
173 }
174
Release()175 void CodeGenModule::Release() {
176 EmitDeferred();
177 EmitCXXGlobalInitFunc();
178 EmitCXXGlobalDtorFunc();
179 EmitCXXThreadLocalInitFunc();
180 if (ObjCRuntime)
181 if (llvm::Function *ObjCInitFunction = ObjCRuntime->ModuleInitFunction())
182 AddGlobalCtor(ObjCInitFunction);
183 EmitCtorList(GlobalCtors, "llvm.global_ctors");
184 EmitCtorList(GlobalDtors, "llvm.global_dtors");
185 EmitGlobalAnnotations();
186 EmitStaticExternCAliases();
187 EmitLLVMUsed();
188
189 if (CodeGenOpts.Autolink &&
190 (Context.getLangOpts().Modules || !LinkerOptionsMetadata.empty())) {
191 EmitModuleLinkOptions();
192 }
193 if (CodeGenOpts.DwarfVersion)
194 // We actually want the latest version when there are conflicts.
195 // We can change from Warning to Latest if such mode is supported.
196 getModule().addModuleFlag(llvm::Module::Warning, "Dwarf Version",
197 CodeGenOpts.DwarfVersion);
198
199 SimplifyPersonality();
200
201 if (getCodeGenOpts().EmitDeclMetadata)
202 EmitDeclMetadata();
203
204 if (getCodeGenOpts().EmitGcovArcs || getCodeGenOpts().EmitGcovNotes)
205 EmitCoverageFile();
206
207 if (DebugInfo)
208 DebugInfo->finalize();
209 }
210
UpdateCompletedType(const TagDecl * TD)211 void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
212 // Make sure that this type is translated.
213 Types.UpdateCompletedType(TD);
214 }
215
getTBAAInfo(QualType QTy)216 llvm::MDNode *CodeGenModule::getTBAAInfo(QualType QTy) {
217 if (!TBAA)
218 return 0;
219 return TBAA->getTBAAInfo(QTy);
220 }
221
getTBAAInfoForVTablePtr()222 llvm::MDNode *CodeGenModule::getTBAAInfoForVTablePtr() {
223 if (!TBAA)
224 return 0;
225 return TBAA->getTBAAInfoForVTablePtr();
226 }
227
getTBAAStructInfo(QualType QTy)228 llvm::MDNode *CodeGenModule::getTBAAStructInfo(QualType QTy) {
229 if (!TBAA)
230 return 0;
231 return TBAA->getTBAAStructInfo(QTy);
232 }
233
getTBAAStructTypeInfo(QualType QTy)234 llvm::MDNode *CodeGenModule::getTBAAStructTypeInfo(QualType QTy) {
235 if (!TBAA)
236 return 0;
237 return TBAA->getTBAAStructTypeInfo(QTy);
238 }
239
getTBAAStructTagInfo(QualType BaseTy,llvm::MDNode * AccessN,uint64_t O)240 llvm::MDNode *CodeGenModule::getTBAAStructTagInfo(QualType BaseTy,
241 llvm::MDNode *AccessN,
242 uint64_t O) {
243 if (!TBAA)
244 return 0;
245 return TBAA->getTBAAStructTagInfo(BaseTy, AccessN, O);
246 }
247
248 /// Decorate the instruction with a TBAA tag. For scalar TBAA, the tag
249 /// is the same as the type. For struct-path aware TBAA, the tag
250 /// is different from the type: base type, access type and offset.
251 /// When ConvertTypeToTag is true, we create a tag based on the scalar type.
DecorateInstruction(llvm::Instruction * Inst,llvm::MDNode * TBAAInfo,bool ConvertTypeToTag)252 void CodeGenModule::DecorateInstruction(llvm::Instruction *Inst,
253 llvm::MDNode *TBAAInfo,
254 bool ConvertTypeToTag) {
255 if (ConvertTypeToTag && TBAA && CodeGenOpts.StructPathTBAA)
256 Inst->setMetadata(llvm::LLVMContext::MD_tbaa,
257 TBAA->getTBAAScalarTagInfo(TBAAInfo));
258 else
259 Inst->setMetadata(llvm::LLVMContext::MD_tbaa, TBAAInfo);
260 }
261
Error(SourceLocation loc,StringRef error)262 void CodeGenModule::Error(SourceLocation loc, StringRef error) {
263 unsigned diagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, error);
264 getDiags().Report(Context.getFullLoc(loc), diagID);
265 }
266
267 /// ErrorUnsupported - Print out an error that codegen doesn't support the
268 /// specified stmt yet.
ErrorUnsupported(const Stmt * S,const char * Type,bool OmitOnError)269 void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type,
270 bool OmitOnError) {
271 if (OmitOnError && getDiags().hasErrorOccurred())
272 return;
273 unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
274 "cannot compile this %0 yet");
275 std::string Msg = Type;
276 getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID)
277 << Msg << S->getSourceRange();
278 }
279
280 /// ErrorUnsupported - Print out an error that codegen doesn't support the
281 /// specified decl yet.
ErrorUnsupported(const Decl * D,const char * Type,bool OmitOnError)282 void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type,
283 bool OmitOnError) {
284 if (OmitOnError && getDiags().hasErrorOccurred())
285 return;
286 unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
287 "cannot compile this %0 yet");
288 std::string Msg = Type;
289 getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg;
290 }
291
getSize(CharUnits size)292 llvm::ConstantInt *CodeGenModule::getSize(CharUnits size) {
293 return llvm::ConstantInt::get(SizeTy, size.getQuantity());
294 }
295
setGlobalVisibility(llvm::GlobalValue * GV,const NamedDecl * D) const296 void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV,
297 const NamedDecl *D) const {
298 // Internal definitions always have default visibility.
299 if (GV->hasLocalLinkage()) {
300 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
301 return;
302 }
303
304 // Set visibility for definitions.
305 LinkageInfo LV = D->getLinkageAndVisibility();
306 if (LV.isVisibilityExplicit() || !GV->hasAvailableExternallyLinkage())
307 GV->setVisibility(GetLLVMVisibility(LV.getVisibility()));
308 }
309
GetLLVMTLSModel(StringRef S)310 static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(StringRef S) {
311 return llvm::StringSwitch<llvm::GlobalVariable::ThreadLocalMode>(S)
312 .Case("global-dynamic", llvm::GlobalVariable::GeneralDynamicTLSModel)
313 .Case("local-dynamic", llvm::GlobalVariable::LocalDynamicTLSModel)
314 .Case("initial-exec", llvm::GlobalVariable::InitialExecTLSModel)
315 .Case("local-exec", llvm::GlobalVariable::LocalExecTLSModel);
316 }
317
GetLLVMTLSModel(CodeGenOptions::TLSModel M)318 static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(
319 CodeGenOptions::TLSModel M) {
320 switch (M) {
321 case CodeGenOptions::GeneralDynamicTLSModel:
322 return llvm::GlobalVariable::GeneralDynamicTLSModel;
323 case CodeGenOptions::LocalDynamicTLSModel:
324 return llvm::GlobalVariable::LocalDynamicTLSModel;
325 case CodeGenOptions::InitialExecTLSModel:
326 return llvm::GlobalVariable::InitialExecTLSModel;
327 case CodeGenOptions::LocalExecTLSModel:
328 return llvm::GlobalVariable::LocalExecTLSModel;
329 }
330 llvm_unreachable("Invalid TLS model!");
331 }
332
setTLSMode(llvm::GlobalVariable * GV,const VarDecl & D) const333 void CodeGenModule::setTLSMode(llvm::GlobalVariable *GV,
334 const VarDecl &D) const {
335 assert(D.getTLSKind() && "setting TLS mode on non-TLS var!");
336
337 llvm::GlobalVariable::ThreadLocalMode TLM;
338 TLM = GetLLVMTLSModel(CodeGenOpts.getDefaultTLSModel());
339
340 // Override the TLS model if it is explicitly specified.
341 if (D.hasAttr<TLSModelAttr>()) {
342 const TLSModelAttr *Attr = D.getAttr<TLSModelAttr>();
343 TLM = GetLLVMTLSModel(Attr->getModel());
344 }
345
346 GV->setThreadLocalMode(TLM);
347 }
348
349 /// Set the symbol visibility of type information (vtable and RTTI)
350 /// associated with the given type.
setTypeVisibility(llvm::GlobalValue * GV,const CXXRecordDecl * RD,TypeVisibilityKind TVK) const351 void CodeGenModule::setTypeVisibility(llvm::GlobalValue *GV,
352 const CXXRecordDecl *RD,
353 TypeVisibilityKind TVK) const {
354 setGlobalVisibility(GV, RD);
355
356 if (!CodeGenOpts.HiddenWeakVTables)
357 return;
358
359 // We never want to drop the visibility for RTTI names.
360 if (TVK == TVK_ForRTTIName)
361 return;
362
363 // We want to drop the visibility to hidden for weak type symbols.
364 // This isn't possible if there might be unresolved references
365 // elsewhere that rely on this symbol being visible.
366
367 // This should be kept roughly in sync with setThunkVisibility
368 // in CGVTables.cpp.
369
370 // Preconditions.
371 if (GV->getLinkage() != llvm::GlobalVariable::LinkOnceODRLinkage ||
372 GV->getVisibility() != llvm::GlobalVariable::DefaultVisibility)
373 return;
374
375 // Don't override an explicit visibility attribute.
376 if (RD->getExplicitVisibility(NamedDecl::VisibilityForType))
377 return;
378
379 switch (RD->getTemplateSpecializationKind()) {
380 // We have to disable the optimization if this is an EI definition
381 // because there might be EI declarations in other shared objects.
382 case TSK_ExplicitInstantiationDefinition:
383 case TSK_ExplicitInstantiationDeclaration:
384 return;
385
386 // Every use of a non-template class's type information has to emit it.
387 case TSK_Undeclared:
388 break;
389
390 // In theory, implicit instantiations can ignore the possibility of
391 // an explicit instantiation declaration because there necessarily
392 // must be an EI definition somewhere with default visibility. In
393 // practice, it's possible to have an explicit instantiation for
394 // an arbitrary template class, and linkers aren't necessarily able
395 // to deal with mixed-visibility symbols.
396 case TSK_ExplicitSpecialization:
397 case TSK_ImplicitInstantiation:
398 return;
399 }
400
401 // If there's a key function, there may be translation units
402 // that don't have the key function's definition. But ignore
403 // this if we're emitting RTTI under -fno-rtti.
404 if (!(TVK != TVK_ForRTTI) || LangOpts.RTTI) {
405 // FIXME: what should we do if we "lose" the key function during
406 // the emission of the file?
407 if (Context.getCurrentKeyFunction(RD))
408 return;
409 }
410
411 // Otherwise, drop the visibility to hidden.
412 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
413 GV->setUnnamedAddr(true);
414 }
415
getMangledName(GlobalDecl GD)416 StringRef CodeGenModule::getMangledName(GlobalDecl GD) {
417 const NamedDecl *ND = cast<NamedDecl>(GD.getDecl());
418
419 StringRef &Str = MangledDeclNames[GD.getCanonicalDecl()];
420 if (!Str.empty())
421 return Str;
422
423 if (!getCXXABI().getMangleContext().shouldMangleDeclName(ND)) {
424 IdentifierInfo *II = ND->getIdentifier();
425 assert(II && "Attempt to mangle unnamed decl.");
426
427 Str = II->getName();
428 return Str;
429 }
430
431 SmallString<256> Buffer;
432 llvm::raw_svector_ostream Out(Buffer);
433 if (const CXXConstructorDecl *D = dyn_cast<CXXConstructorDecl>(ND))
434 getCXXABI().getMangleContext().mangleCXXCtor(D, GD.getCtorType(), Out);
435 else if (const CXXDestructorDecl *D = dyn_cast<CXXDestructorDecl>(ND))
436 getCXXABI().getMangleContext().mangleCXXDtor(D, GD.getDtorType(), Out);
437 else
438 getCXXABI().getMangleContext().mangleName(ND, Out);
439
440 // Allocate space for the mangled name.
441 Out.flush();
442 size_t Length = Buffer.size();
443 char *Name = MangledNamesAllocator.Allocate<char>(Length);
444 std::copy(Buffer.begin(), Buffer.end(), Name);
445
446 Str = StringRef(Name, Length);
447
448 return Str;
449 }
450
getBlockMangledName(GlobalDecl GD,MangleBuffer & Buffer,const BlockDecl * BD)451 void CodeGenModule::getBlockMangledName(GlobalDecl GD, MangleBuffer &Buffer,
452 const BlockDecl *BD) {
453 MangleContext &MangleCtx = getCXXABI().getMangleContext();
454 const Decl *D = GD.getDecl();
455 llvm::raw_svector_ostream Out(Buffer.getBuffer());
456 if (D == 0)
457 MangleCtx.mangleGlobalBlock(BD,
458 dyn_cast_or_null<VarDecl>(initializedGlobalDecl.getDecl()), Out);
459 else if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
460 MangleCtx.mangleCtorBlock(CD, GD.getCtorType(), BD, Out);
461 else if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(D))
462 MangleCtx.mangleDtorBlock(DD, GD.getDtorType(), BD, Out);
463 else
464 MangleCtx.mangleBlock(cast<DeclContext>(D), BD, Out);
465 }
466
GetGlobalValue(StringRef Name)467 llvm::GlobalValue *CodeGenModule::GetGlobalValue(StringRef Name) {
468 return getModule().getNamedValue(Name);
469 }
470
471 /// AddGlobalCtor - Add a function to the list that will be called before
472 /// main() runs.
AddGlobalCtor(llvm::Function * Ctor,int Priority)473 void CodeGenModule::AddGlobalCtor(llvm::Function * Ctor, int Priority) {
474 // FIXME: Type coercion of void()* types.
475 GlobalCtors.push_back(std::make_pair(Ctor, Priority));
476 }
477
478 /// AddGlobalDtor - Add a function to the list that will be called
479 /// when the module is unloaded.
AddGlobalDtor(llvm::Function * Dtor,int Priority)480 void CodeGenModule::AddGlobalDtor(llvm::Function * Dtor, int Priority) {
481 // FIXME: Type coercion of void()* types.
482 GlobalDtors.push_back(std::make_pair(Dtor, Priority));
483 }
484
EmitCtorList(const CtorList & Fns,const char * GlobalName)485 void CodeGenModule::EmitCtorList(const CtorList &Fns, const char *GlobalName) {
486 // Ctor function type is void()*.
487 llvm::FunctionType* CtorFTy = llvm::FunctionType::get(VoidTy, false);
488 llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy);
489
490 // Get the type of a ctor entry, { i32, void ()* }.
491 llvm::StructType *CtorStructTy =
492 llvm::StructType::get(Int32Ty, llvm::PointerType::getUnqual(CtorFTy), NULL);
493
494 // Construct the constructor and destructor arrays.
495 SmallVector<llvm::Constant*, 8> Ctors;
496 for (CtorList::const_iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
497 llvm::Constant *S[] = {
498 llvm::ConstantInt::get(Int32Ty, I->second, false),
499 llvm::ConstantExpr::getBitCast(I->first, CtorPFTy)
500 };
501 Ctors.push_back(llvm::ConstantStruct::get(CtorStructTy, S));
502 }
503
504 if (!Ctors.empty()) {
505 llvm::ArrayType *AT = llvm::ArrayType::get(CtorStructTy, Ctors.size());
506 new llvm::GlobalVariable(TheModule, AT, false,
507 llvm::GlobalValue::AppendingLinkage,
508 llvm::ConstantArray::get(AT, Ctors),
509 GlobalName);
510 }
511 }
512
513 llvm::GlobalValue::LinkageTypes
getFunctionLinkage(GlobalDecl GD)514 CodeGenModule::getFunctionLinkage(GlobalDecl GD) {
515 const FunctionDecl *D = cast<FunctionDecl>(GD.getDecl());
516
517 if (isa<CXXDestructorDecl>(D) &&
518 getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D),
519 GD.getDtorType()))
520 return llvm::Function::LinkOnceODRLinkage;
521
522 GVALinkage Linkage = getContext().GetGVALinkageForFunction(D);
523
524 if (Linkage == GVA_Internal)
525 return llvm::Function::InternalLinkage;
526
527 if (D->hasAttr<DLLExportAttr>())
528 return llvm::Function::DLLExportLinkage;
529
530 if (D->hasAttr<WeakAttr>())
531 return llvm::Function::WeakAnyLinkage;
532
533 // In C99 mode, 'inline' functions are guaranteed to have a strong
534 // definition somewhere else, so we can use available_externally linkage.
535 if (Linkage == GVA_C99Inline)
536 return llvm::Function::AvailableExternallyLinkage;
537
538 // Note that Apple's kernel linker doesn't support symbol
539 // coalescing, so we need to avoid linkonce and weak linkages there.
540 // Normally, this means we just map to internal, but for explicit
541 // instantiations we'll map to external.
542
543 // In C++, the compiler has to emit a definition in every translation unit
544 // that references the function. We should use linkonce_odr because
545 // a) if all references in this translation unit are optimized away, we
546 // don't need to codegen it. b) if the function persists, it needs to be
547 // merged with other definitions. c) C++ has the ODR, so we know the
548 // definition is dependable.
549 if (Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
550 return !Context.getLangOpts().AppleKext
551 ? llvm::Function::LinkOnceODRLinkage
552 : llvm::Function::InternalLinkage;
553
554 // An explicit instantiation of a template has weak linkage, since
555 // explicit instantiations can occur in multiple translation units
556 // and must all be equivalent. However, we are not allowed to
557 // throw away these explicit instantiations.
558 if (Linkage == GVA_ExplicitTemplateInstantiation)
559 return !Context.getLangOpts().AppleKext
560 ? llvm::Function::WeakODRLinkage
561 : llvm::Function::ExternalLinkage;
562
563 // Otherwise, we have strong external linkage.
564 assert(Linkage == GVA_StrongExternal);
565 return llvm::Function::ExternalLinkage;
566 }
567
568
569 /// SetFunctionDefinitionAttributes - Set attributes for a global.
570 ///
571 /// FIXME: This is currently only done for aliases and functions, but not for
572 /// variables (these details are set in EmitGlobalVarDefinition for variables).
SetFunctionDefinitionAttributes(const FunctionDecl * D,llvm::GlobalValue * GV)573 void CodeGenModule::SetFunctionDefinitionAttributes(const FunctionDecl *D,
574 llvm::GlobalValue *GV) {
575 SetCommonAttributes(D, GV);
576 }
577
SetLLVMFunctionAttributes(const Decl * D,const CGFunctionInfo & Info,llvm::Function * F)578 void CodeGenModule::SetLLVMFunctionAttributes(const Decl *D,
579 const CGFunctionInfo &Info,
580 llvm::Function *F) {
581 unsigned CallingConv;
582 AttributeListType AttributeList;
583 ConstructAttributeList(Info, D, AttributeList, CallingConv, false);
584 F->setAttributes(llvm::AttributeSet::get(getLLVMContext(), AttributeList));
585 F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
586 }
587
588 /// Determines whether the language options require us to model
589 /// unwind exceptions. We treat -fexceptions as mandating this
590 /// except under the fragile ObjC ABI with only ObjC exceptions
591 /// enabled. This means, for example, that C with -fexceptions
592 /// enables this.
hasUnwindExceptions(const LangOptions & LangOpts)593 static bool hasUnwindExceptions(const LangOptions &LangOpts) {
594 // If exceptions are completely disabled, obviously this is false.
595 if (!LangOpts.Exceptions) return false;
596
597 // If C++ exceptions are enabled, this is true.
598 if (LangOpts.CXXExceptions) return true;
599
600 // If ObjC exceptions are enabled, this depends on the ABI.
601 if (LangOpts.ObjCExceptions) {
602 return LangOpts.ObjCRuntime.hasUnwindExceptions();
603 }
604
605 return true;
606 }
607
SetLLVMFunctionAttributesForDefinition(const Decl * D,llvm::Function * F)608 void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D,
609 llvm::Function *F) {
610 llvm::AttrBuilder B;
611
612 if (CodeGenOpts.UnwindTables)
613 B.addAttribute(llvm::Attribute::UWTable);
614
615 if (!hasUnwindExceptions(LangOpts))
616 B.addAttribute(llvm::Attribute::NoUnwind);
617
618 if (D->hasAttr<NakedAttr>()) {
619 // Naked implies noinline: we should not be inlining such functions.
620 B.addAttribute(llvm::Attribute::Naked);
621 B.addAttribute(llvm::Attribute::NoInline);
622 } else if (D->hasAttr<NoInlineAttr>()) {
623 B.addAttribute(llvm::Attribute::NoInline);
624 } else if ((D->hasAttr<AlwaysInlineAttr>() ||
625 D->hasAttr<ForceInlineAttr>()) &&
626 !F->getAttributes().hasAttribute(llvm::AttributeSet::FunctionIndex,
627 llvm::Attribute::NoInline)) {
628 // (noinline wins over always_inline, and we can't specify both in IR)
629 B.addAttribute(llvm::Attribute::AlwaysInline);
630 }
631
632 if (D->hasAttr<ColdAttr>()) {
633 B.addAttribute(llvm::Attribute::OptimizeForSize);
634 B.addAttribute(llvm::Attribute::Cold);
635 }
636
637 if (D->hasAttr<MinSizeAttr>())
638 B.addAttribute(llvm::Attribute::MinSize);
639
640 if (LangOpts.getStackProtector() == LangOptions::SSPOn)
641 B.addAttribute(llvm::Attribute::StackProtect);
642 else if (LangOpts.getStackProtector() == LangOptions::SSPReq)
643 B.addAttribute(llvm::Attribute::StackProtectReq);
644
645 // Add sanitizer attributes if function is not blacklisted.
646 if (!SanitizerBlacklist.isIn(*F)) {
647 // When AddressSanitizer is enabled, set SanitizeAddress attribute
648 // unless __attribute__((no_sanitize_address)) is used.
649 if (SanOpts.Address && !D->hasAttr<NoSanitizeAddressAttr>())
650 B.addAttribute(llvm::Attribute::SanitizeAddress);
651 // Same for ThreadSanitizer and __attribute__((no_sanitize_thread))
652 if (SanOpts.Thread && !D->hasAttr<NoSanitizeThreadAttr>()) {
653 B.addAttribute(llvm::Attribute::SanitizeThread);
654 }
655 // Same for MemorySanitizer and __attribute__((no_sanitize_memory))
656 if (SanOpts.Memory && !D->hasAttr<NoSanitizeMemoryAttr>())
657 B.addAttribute(llvm::Attribute::SanitizeMemory);
658 }
659
660 F->addAttributes(llvm::AttributeSet::FunctionIndex,
661 llvm::AttributeSet::get(
662 F->getContext(), llvm::AttributeSet::FunctionIndex, B));
663
664 if (isa<CXXConstructorDecl>(D) || isa<CXXDestructorDecl>(D))
665 F->setUnnamedAddr(true);
666 else if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D))
667 if (MD->isVirtual())
668 F->setUnnamedAddr(true);
669
670 unsigned alignment = D->getMaxAlignment() / Context.getCharWidth();
671 if (alignment)
672 F->setAlignment(alignment);
673
674 // C++ ABI requires 2-byte alignment for member functions.
675 if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D))
676 F->setAlignment(2);
677 }
678
SetCommonAttributes(const Decl * D,llvm::GlobalValue * GV)679 void CodeGenModule::SetCommonAttributes(const Decl *D,
680 llvm::GlobalValue *GV) {
681 if (const NamedDecl *ND = dyn_cast<NamedDecl>(D))
682 setGlobalVisibility(GV, ND);
683 else
684 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
685
686 if (D->hasAttr<UsedAttr>())
687 AddUsedGlobal(GV);
688
689 if (const SectionAttr *SA = D->getAttr<SectionAttr>())
690 GV->setSection(SA->getName());
691
692 // Alias cannot have attributes. Filter them here.
693 if (!isa<llvm::GlobalAlias>(GV))
694 getTargetCodeGenInfo().SetTargetAttributes(D, GV, *this);
695 }
696
SetInternalFunctionAttributes(const Decl * D,llvm::Function * F,const CGFunctionInfo & FI)697 void CodeGenModule::SetInternalFunctionAttributes(const Decl *D,
698 llvm::Function *F,
699 const CGFunctionInfo &FI) {
700 SetLLVMFunctionAttributes(D, FI, F);
701 SetLLVMFunctionAttributesForDefinition(D, F);
702
703 F->setLinkage(llvm::Function::InternalLinkage);
704
705 SetCommonAttributes(D, F);
706 }
707
SetFunctionAttributes(GlobalDecl GD,llvm::Function * F,bool IsIncompleteFunction)708 void CodeGenModule::SetFunctionAttributes(GlobalDecl GD,
709 llvm::Function *F,
710 bool IsIncompleteFunction) {
711 if (unsigned IID = F->getIntrinsicID()) {
712 // If this is an intrinsic function, set the function's attributes
713 // to the intrinsic's attributes.
714 F->setAttributes(llvm::Intrinsic::getAttributes(getLLVMContext(),
715 (llvm::Intrinsic::ID)IID));
716 return;
717 }
718
719 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
720
721 if (!IsIncompleteFunction)
722 SetLLVMFunctionAttributes(FD, getTypes().arrangeGlobalDeclaration(GD), F);
723
724 if (getCXXABI().HasThisReturn(GD)) {
725 assert(!F->arg_empty() &&
726 F->arg_begin()->getType()
727 ->canLosslesslyBitCastTo(F->getReturnType()) &&
728 "unexpected this return");
729 F->addAttribute(1, llvm::Attribute::Returned);
730 }
731
732 // Only a few attributes are set on declarations; these may later be
733 // overridden by a definition.
734
735 if (FD->hasAttr<DLLImportAttr>()) {
736 F->setLinkage(llvm::Function::DLLImportLinkage);
737 } else if (FD->hasAttr<WeakAttr>() ||
738 FD->isWeakImported()) {
739 // "extern_weak" is overloaded in LLVM; we probably should have
740 // separate linkage types for this.
741 F->setLinkage(llvm::Function::ExternalWeakLinkage);
742 } else {
743 F->setLinkage(llvm::Function::ExternalLinkage);
744
745 LinkageInfo LV = FD->getLinkageAndVisibility();
746 if (LV.getLinkage() == ExternalLinkage && LV.isVisibilityExplicit()) {
747 F->setVisibility(GetLLVMVisibility(LV.getVisibility()));
748 }
749 }
750
751 if (const SectionAttr *SA = FD->getAttr<SectionAttr>())
752 F->setSection(SA->getName());
753
754 // A replaceable global allocation function does not act like a builtin by
755 // default, only if it is invoked by a new-expression or delete-expression.
756 if (FD->isReplaceableGlobalAllocationFunction())
757 F->addAttribute(llvm::AttributeSet::FunctionIndex,
758 llvm::Attribute::NoBuiltin);
759 }
760
AddUsedGlobal(llvm::GlobalValue * GV)761 void CodeGenModule::AddUsedGlobal(llvm::GlobalValue *GV) {
762 assert(!GV->isDeclaration() &&
763 "Only globals with definition can force usage.");
764 LLVMUsed.push_back(GV);
765 }
766
EmitLLVMUsed()767 void CodeGenModule::EmitLLVMUsed() {
768 // Don't create llvm.used if there is no need.
769 if (LLVMUsed.empty())
770 return;
771
772 // Convert LLVMUsed to what ConstantArray needs.
773 SmallVector<llvm::Constant*, 8> UsedArray;
774 UsedArray.resize(LLVMUsed.size());
775 for (unsigned i = 0, e = LLVMUsed.size(); i != e; ++i) {
776 UsedArray[i] =
777 llvm::ConstantExpr::getBitCast(cast<llvm::Constant>(&*LLVMUsed[i]),
778 Int8PtrTy);
779 }
780
781 if (UsedArray.empty())
782 return;
783 llvm::ArrayType *ATy = llvm::ArrayType::get(Int8PtrTy, UsedArray.size());
784
785 llvm::GlobalVariable *GV =
786 new llvm::GlobalVariable(getModule(), ATy, false,
787 llvm::GlobalValue::AppendingLinkage,
788 llvm::ConstantArray::get(ATy, UsedArray),
789 "llvm.used");
790
791 GV->setSection("llvm.metadata");
792 }
793
AppendLinkerOptions(StringRef Opts)794 void CodeGenModule::AppendLinkerOptions(StringRef Opts) {
795 llvm::Value *MDOpts = llvm::MDString::get(getLLVMContext(), Opts);
796 LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
797 }
798
AddDetectMismatch(StringRef Name,StringRef Value)799 void CodeGenModule::AddDetectMismatch(StringRef Name, StringRef Value) {
800 llvm::SmallString<32> Opt;
801 getTargetCodeGenInfo().getDetectMismatchOption(Name, Value, Opt);
802 llvm::Value *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
803 LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
804 }
805
AddDependentLib(StringRef Lib)806 void CodeGenModule::AddDependentLib(StringRef Lib) {
807 llvm::SmallString<24> Opt;
808 getTargetCodeGenInfo().getDependentLibraryOption(Lib, Opt);
809 llvm::Value *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
810 LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
811 }
812
813 /// \brief Add link options implied by the given module, including modules
814 /// it depends on, using a postorder walk.
addLinkOptionsPostorder(CodeGenModule & CGM,Module * Mod,SmallVectorImpl<llvm::Value * > & Metadata,llvm::SmallPtrSet<Module *,16> & Visited)815 static void addLinkOptionsPostorder(CodeGenModule &CGM,
816 Module *Mod,
817 SmallVectorImpl<llvm::Value *> &Metadata,
818 llvm::SmallPtrSet<Module *, 16> &Visited) {
819 // Import this module's parent.
820 if (Mod->Parent && Visited.insert(Mod->Parent)) {
821 addLinkOptionsPostorder(CGM, Mod->Parent, Metadata, Visited);
822 }
823
824 // Import this module's dependencies.
825 for (unsigned I = Mod->Imports.size(); I > 0; --I) {
826 if (Visited.insert(Mod->Imports[I-1]))
827 addLinkOptionsPostorder(CGM, Mod->Imports[I-1], Metadata, Visited);
828 }
829
830 // Add linker options to link against the libraries/frameworks
831 // described by this module.
832 llvm::LLVMContext &Context = CGM.getLLVMContext();
833 for (unsigned I = Mod->LinkLibraries.size(); I > 0; --I) {
834 // Link against a framework. Frameworks are currently Darwin only, so we
835 // don't to ask TargetCodeGenInfo for the spelling of the linker option.
836 if (Mod->LinkLibraries[I-1].IsFramework) {
837 llvm::Value *Args[2] = {
838 llvm::MDString::get(Context, "-framework"),
839 llvm::MDString::get(Context, Mod->LinkLibraries[I-1].Library)
840 };
841
842 Metadata.push_back(llvm::MDNode::get(Context, Args));
843 continue;
844 }
845
846 // Link against a library.
847 llvm::SmallString<24> Opt;
848 CGM.getTargetCodeGenInfo().getDependentLibraryOption(
849 Mod->LinkLibraries[I-1].Library, Opt);
850 llvm::Value *OptString = llvm::MDString::get(Context, Opt);
851 Metadata.push_back(llvm::MDNode::get(Context, OptString));
852 }
853 }
854
EmitModuleLinkOptions()855 void CodeGenModule::EmitModuleLinkOptions() {
856 // Collect the set of all of the modules we want to visit to emit link
857 // options, which is essentially the imported modules and all of their
858 // non-explicit child modules.
859 llvm::SetVector<clang::Module *> LinkModules;
860 llvm::SmallPtrSet<clang::Module *, 16> Visited;
861 SmallVector<clang::Module *, 16> Stack;
862
863 // Seed the stack with imported modules.
864 for (llvm::SetVector<clang::Module *>::iterator M = ImportedModules.begin(),
865 MEnd = ImportedModules.end();
866 M != MEnd; ++M) {
867 if (Visited.insert(*M))
868 Stack.push_back(*M);
869 }
870
871 // Find all of the modules to import, making a little effort to prune
872 // non-leaf modules.
873 while (!Stack.empty()) {
874 clang::Module *Mod = Stack.back();
875 Stack.pop_back();
876
877 bool AnyChildren = false;
878
879 // Visit the submodules of this module.
880 for (clang::Module::submodule_iterator Sub = Mod->submodule_begin(),
881 SubEnd = Mod->submodule_end();
882 Sub != SubEnd; ++Sub) {
883 // Skip explicit children; they need to be explicitly imported to be
884 // linked against.
885 if ((*Sub)->IsExplicit)
886 continue;
887
888 if (Visited.insert(*Sub)) {
889 Stack.push_back(*Sub);
890 AnyChildren = true;
891 }
892 }
893
894 // We didn't find any children, so add this module to the list of
895 // modules to link against.
896 if (!AnyChildren) {
897 LinkModules.insert(Mod);
898 }
899 }
900
901 // Add link options for all of the imported modules in reverse topological
902 // order. We don't do anything to try to order import link flags with respect
903 // to linker options inserted by things like #pragma comment().
904 SmallVector<llvm::Value *, 16> MetadataArgs;
905 Visited.clear();
906 for (llvm::SetVector<clang::Module *>::iterator M = LinkModules.begin(),
907 MEnd = LinkModules.end();
908 M != MEnd; ++M) {
909 if (Visited.insert(*M))
910 addLinkOptionsPostorder(*this, *M, MetadataArgs, Visited);
911 }
912 std::reverse(MetadataArgs.begin(), MetadataArgs.end());
913 LinkerOptionsMetadata.append(MetadataArgs.begin(), MetadataArgs.end());
914
915 // Add the linker options metadata flag.
916 getModule().addModuleFlag(llvm::Module::AppendUnique, "Linker Options",
917 llvm::MDNode::get(getLLVMContext(),
918 LinkerOptionsMetadata));
919 }
920
EmitDeferred()921 void CodeGenModule::EmitDeferred() {
922 // Emit code for any potentially referenced deferred decls. Since a
923 // previously unused static decl may become used during the generation of code
924 // for a static function, iterate until no changes are made.
925
926 while (true) {
927 if (!DeferredVTables.empty()) {
928 EmitDeferredVTables();
929
930 // Emitting a v-table doesn't directly cause more v-tables to
931 // become deferred, although it can cause functions to be
932 // emitted that then need those v-tables.
933 assert(DeferredVTables.empty());
934 }
935
936 // Stop if we're out of both deferred v-tables and deferred declarations.
937 if (DeferredDeclsToEmit.empty()) break;
938
939 GlobalDecl D = DeferredDeclsToEmit.back();
940 DeferredDeclsToEmit.pop_back();
941
942 // Check to see if we've already emitted this. This is necessary
943 // for a couple of reasons: first, decls can end up in the
944 // deferred-decls queue multiple times, and second, decls can end
945 // up with definitions in unusual ways (e.g. by an extern inline
946 // function acquiring a strong function redefinition). Just
947 // ignore these cases.
948 //
949 // TODO: That said, looking this up multiple times is very wasteful.
950 StringRef Name = getMangledName(D);
951 llvm::GlobalValue *CGRef = GetGlobalValue(Name);
952 assert(CGRef && "Deferred decl wasn't referenced?");
953
954 if (!CGRef->isDeclaration())
955 continue;
956
957 // GlobalAlias::isDeclaration() defers to the aliasee, but for our
958 // purposes an alias counts as a definition.
959 if (isa<llvm::GlobalAlias>(CGRef))
960 continue;
961
962 // Otherwise, emit the definition and move on to the next one.
963 EmitGlobalDefinition(D);
964 }
965 }
966
EmitGlobalAnnotations()967 void CodeGenModule::EmitGlobalAnnotations() {
968 if (Annotations.empty())
969 return;
970
971 // Create a new global variable for the ConstantStruct in the Module.
972 llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get(
973 Annotations[0]->getType(), Annotations.size()), Annotations);
974 llvm::GlobalValue *gv = new llvm::GlobalVariable(getModule(),
975 Array->getType(), false, llvm::GlobalValue::AppendingLinkage, Array,
976 "llvm.global.annotations");
977 gv->setSection(AnnotationSection);
978 }
979
EmitAnnotationString(StringRef Str)980 llvm::Constant *CodeGenModule::EmitAnnotationString(StringRef Str) {
981 llvm::StringMap<llvm::Constant*>::iterator i = AnnotationStrings.find(Str);
982 if (i != AnnotationStrings.end())
983 return i->second;
984
985 // Not found yet, create a new global.
986 llvm::Constant *s = llvm::ConstantDataArray::getString(getLLVMContext(), Str);
987 llvm::GlobalValue *gv = new llvm::GlobalVariable(getModule(), s->getType(),
988 true, llvm::GlobalValue::PrivateLinkage, s, ".str");
989 gv->setSection(AnnotationSection);
990 gv->setUnnamedAddr(true);
991 AnnotationStrings[Str] = gv;
992 return gv;
993 }
994
EmitAnnotationUnit(SourceLocation Loc)995 llvm::Constant *CodeGenModule::EmitAnnotationUnit(SourceLocation Loc) {
996 SourceManager &SM = getContext().getSourceManager();
997 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
998 if (PLoc.isValid())
999 return EmitAnnotationString(PLoc.getFilename());
1000 return EmitAnnotationString(SM.getBufferName(Loc));
1001 }
1002
EmitAnnotationLineNo(SourceLocation L)1003 llvm::Constant *CodeGenModule::EmitAnnotationLineNo(SourceLocation L) {
1004 SourceManager &SM = getContext().getSourceManager();
1005 PresumedLoc PLoc = SM.getPresumedLoc(L);
1006 unsigned LineNo = PLoc.isValid() ? PLoc.getLine() :
1007 SM.getExpansionLineNumber(L);
1008 return llvm::ConstantInt::get(Int32Ty, LineNo);
1009 }
1010
EmitAnnotateAttr(llvm::GlobalValue * GV,const AnnotateAttr * AA,SourceLocation L)1011 llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
1012 const AnnotateAttr *AA,
1013 SourceLocation L) {
1014 // Get the globals for file name, annotation, and the line number.
1015 llvm::Constant *AnnoGV = EmitAnnotationString(AA->getAnnotation()),
1016 *UnitGV = EmitAnnotationUnit(L),
1017 *LineNoCst = EmitAnnotationLineNo(L);
1018
1019 // Create the ConstantStruct for the global annotation.
1020 llvm::Constant *Fields[4] = {
1021 llvm::ConstantExpr::getBitCast(GV, Int8PtrTy),
1022 llvm::ConstantExpr::getBitCast(AnnoGV, Int8PtrTy),
1023 llvm::ConstantExpr::getBitCast(UnitGV, Int8PtrTy),
1024 LineNoCst
1025 };
1026 return llvm::ConstantStruct::getAnon(Fields);
1027 }
1028
AddGlobalAnnotations(const ValueDecl * D,llvm::GlobalValue * GV)1029 void CodeGenModule::AddGlobalAnnotations(const ValueDecl *D,
1030 llvm::GlobalValue *GV) {
1031 assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
1032 // Get the struct elements for these annotations.
1033 for (specific_attr_iterator<AnnotateAttr>
1034 ai = D->specific_attr_begin<AnnotateAttr>(),
1035 ae = D->specific_attr_end<AnnotateAttr>(); ai != ae; ++ai)
1036 Annotations.push_back(EmitAnnotateAttr(GV, *ai, D->getLocation()));
1037 }
1038
MayDeferGeneration(const ValueDecl * Global)1039 bool CodeGenModule::MayDeferGeneration(const ValueDecl *Global) {
1040 // Never defer when EmitAllDecls is specified.
1041 if (LangOpts.EmitAllDecls)
1042 return false;
1043
1044 return !getContext().DeclMustBeEmitted(Global);
1045 }
1046
GetAddrOfUuidDescriptor(const CXXUuidofExpr * E)1047 llvm::Constant *CodeGenModule::GetAddrOfUuidDescriptor(
1048 const CXXUuidofExpr* E) {
1049 // Sema has verified that IIDSource has a __declspec(uuid()), and that its
1050 // well-formed.
1051 StringRef Uuid;
1052 if (E->isTypeOperand())
1053 Uuid = CXXUuidofExpr::GetUuidAttrOfType(E->getTypeOperand())->getGuid();
1054 else {
1055 // Special case: __uuidof(0) means an all-zero GUID.
1056 Expr *Op = E->getExprOperand();
1057 if (!Op->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
1058 Uuid = CXXUuidofExpr::GetUuidAttrOfType(Op->getType())->getGuid();
1059 else
1060 Uuid = "00000000-0000-0000-0000-000000000000";
1061 }
1062 std::string Name = "__uuid_" + Uuid.str();
1063
1064 // Look for an existing global.
1065 if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name))
1066 return GV;
1067
1068 llvm::Constant *Init = EmitUuidofInitializer(Uuid, E->getType());
1069 assert(Init && "failed to initialize as constant");
1070
1071 // GUIDs are assumed to be 16 bytes, spread over 4-2-2-8 bytes. However, the
1072 // first field is declared as "long", which for many targets is 8 bytes.
1073 // Those architectures are not supported. (With the MS abi, long is always 4
1074 // bytes.)
1075 llvm::Type *GuidType = getTypes().ConvertType(E->getType());
1076 if (Init->getType() != GuidType) {
1077 DiagnosticsEngine &Diags = getDiags();
1078 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1079 "__uuidof codegen is not supported on this architecture");
1080 Diags.Report(E->getExprLoc(), DiagID) << E->getSourceRange();
1081 Init = llvm::UndefValue::get(GuidType);
1082 }
1083
1084 llvm::GlobalVariable *GV = new llvm::GlobalVariable(getModule(), GuidType,
1085 /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage, Init, Name);
1086 GV->setUnnamedAddr(true);
1087 return GV;
1088 }
1089
GetWeakRefReference(const ValueDecl * VD)1090 llvm::Constant *CodeGenModule::GetWeakRefReference(const ValueDecl *VD) {
1091 const AliasAttr *AA = VD->getAttr<AliasAttr>();
1092 assert(AA && "No alias?");
1093
1094 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType());
1095
1096 // See if there is already something with the target's name in the module.
1097 llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee());
1098 if (Entry) {
1099 unsigned AS = getContext().getTargetAddressSpace(VD->getType());
1100 return llvm::ConstantExpr::getBitCast(Entry, DeclTy->getPointerTo(AS));
1101 }
1102
1103 llvm::Constant *Aliasee;
1104 if (isa<llvm::FunctionType>(DeclTy))
1105 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy,
1106 GlobalDecl(cast<FunctionDecl>(VD)),
1107 /*ForVTable=*/false);
1108 else
1109 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
1110 llvm::PointerType::getUnqual(DeclTy), 0);
1111
1112 llvm::GlobalValue* F = cast<llvm::GlobalValue>(Aliasee);
1113 F->setLinkage(llvm::Function::ExternalWeakLinkage);
1114 WeakRefReferences.insert(F);
1115
1116 return Aliasee;
1117 }
1118
EmitGlobal(GlobalDecl GD)1119 void CodeGenModule::EmitGlobal(GlobalDecl GD) {
1120 const ValueDecl *Global = cast<ValueDecl>(GD.getDecl());
1121
1122 // Weak references don't produce any output by themselves.
1123 if (Global->hasAttr<WeakRefAttr>())
1124 return;
1125
1126 // If this is an alias definition (which otherwise looks like a declaration)
1127 // emit it now.
1128 if (Global->hasAttr<AliasAttr>())
1129 return EmitAliasDefinition(GD);
1130
1131 // If this is CUDA, be selective about which declarations we emit.
1132 if (LangOpts.CUDA) {
1133 if (CodeGenOpts.CUDAIsDevice) {
1134 if (!Global->hasAttr<CUDADeviceAttr>() &&
1135 !Global->hasAttr<CUDAGlobalAttr>() &&
1136 !Global->hasAttr<CUDAConstantAttr>() &&
1137 !Global->hasAttr<CUDASharedAttr>())
1138 return;
1139 } else {
1140 if (!Global->hasAttr<CUDAHostAttr>() && (
1141 Global->hasAttr<CUDADeviceAttr>() ||
1142 Global->hasAttr<CUDAConstantAttr>() ||
1143 Global->hasAttr<CUDASharedAttr>()))
1144 return;
1145 }
1146 }
1147
1148 // Ignore declarations, they will be emitted on their first use.
1149 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) {
1150 // Forward declarations are emitted lazily on first use.
1151 if (!FD->doesThisDeclarationHaveABody()) {
1152 if (!FD->doesDeclarationForceExternallyVisibleDefinition())
1153 return;
1154
1155 const FunctionDecl *InlineDefinition = 0;
1156 FD->getBody(InlineDefinition);
1157
1158 StringRef MangledName = getMangledName(GD);
1159 DeferredDecls.erase(MangledName);
1160 EmitGlobalDefinition(InlineDefinition);
1161 return;
1162 }
1163 } else {
1164 const VarDecl *VD = cast<VarDecl>(Global);
1165 assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
1166
1167 if (VD->isThisDeclarationADefinition() != VarDecl::Definition)
1168 return;
1169 }
1170
1171 // Defer code generation when possible if this is a static definition, inline
1172 // function etc. These we only want to emit if they are used.
1173 if (!MayDeferGeneration(Global)) {
1174 // Emit the definition if it can't be deferred.
1175 EmitGlobalDefinition(GD);
1176 return;
1177 }
1178
1179 // If we're deferring emission of a C++ variable with an
1180 // initializer, remember the order in which it appeared in the file.
1181 if (getLangOpts().CPlusPlus && isa<VarDecl>(Global) &&
1182 cast<VarDecl>(Global)->hasInit()) {
1183 DelayedCXXInitPosition[Global] = CXXGlobalInits.size();
1184 CXXGlobalInits.push_back(0);
1185 }
1186
1187 // If the value has already been used, add it directly to the
1188 // DeferredDeclsToEmit list.
1189 StringRef MangledName = getMangledName(GD);
1190 if (GetGlobalValue(MangledName))
1191 DeferredDeclsToEmit.push_back(GD);
1192 else {
1193 // Otherwise, remember that we saw a deferred decl with this name. The
1194 // first use of the mangled name will cause it to move into
1195 // DeferredDeclsToEmit.
1196 DeferredDecls[MangledName] = GD;
1197 }
1198 }
1199
1200 namespace {
1201 struct FunctionIsDirectlyRecursive :
1202 public RecursiveASTVisitor<FunctionIsDirectlyRecursive> {
1203 const StringRef Name;
1204 const Builtin::Context &BI;
1205 bool Result;
FunctionIsDirectlyRecursive__anon0c52fb250111::FunctionIsDirectlyRecursive1206 FunctionIsDirectlyRecursive(StringRef N, const Builtin::Context &C) :
1207 Name(N), BI(C), Result(false) {
1208 }
1209 typedef RecursiveASTVisitor<FunctionIsDirectlyRecursive> Base;
1210
TraverseCallExpr__anon0c52fb250111::FunctionIsDirectlyRecursive1211 bool TraverseCallExpr(CallExpr *E) {
1212 const FunctionDecl *FD = E->getDirectCallee();
1213 if (!FD)
1214 return true;
1215 AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
1216 if (Attr && Name == Attr->getLabel()) {
1217 Result = true;
1218 return false;
1219 }
1220 unsigned BuiltinID = FD->getBuiltinID();
1221 if (!BuiltinID)
1222 return true;
1223 StringRef BuiltinName = BI.GetName(BuiltinID);
1224 if (BuiltinName.startswith("__builtin_") &&
1225 Name == BuiltinName.slice(strlen("__builtin_"), StringRef::npos)) {
1226 Result = true;
1227 return false;
1228 }
1229 return true;
1230 }
1231 };
1232 }
1233
1234 // isTriviallyRecursive - Check if this function calls another
1235 // decl that, because of the asm attribute or the other decl being a builtin,
1236 // ends up pointing to itself.
1237 bool
isTriviallyRecursive(const FunctionDecl * FD)1238 CodeGenModule::isTriviallyRecursive(const FunctionDecl *FD) {
1239 StringRef Name;
1240 if (getCXXABI().getMangleContext().shouldMangleDeclName(FD)) {
1241 // asm labels are a special kind of mangling we have to support.
1242 AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
1243 if (!Attr)
1244 return false;
1245 Name = Attr->getLabel();
1246 } else {
1247 Name = FD->getName();
1248 }
1249
1250 FunctionIsDirectlyRecursive Walker(Name, Context.BuiltinInfo);
1251 Walker.TraverseFunctionDecl(const_cast<FunctionDecl*>(FD));
1252 return Walker.Result;
1253 }
1254
1255 bool
shouldEmitFunction(GlobalDecl GD)1256 CodeGenModule::shouldEmitFunction(GlobalDecl GD) {
1257 if (getFunctionLinkage(GD) != llvm::Function::AvailableExternallyLinkage)
1258 return true;
1259 const FunctionDecl *F = cast<FunctionDecl>(GD.getDecl());
1260 if (CodeGenOpts.OptimizationLevel == 0 &&
1261 !F->hasAttr<AlwaysInlineAttr>() && !F->hasAttr<ForceInlineAttr>())
1262 return false;
1263 // PR9614. Avoid cases where the source code is lying to us. An available
1264 // externally function should have an equivalent function somewhere else,
1265 // but a function that calls itself is clearly not equivalent to the real
1266 // implementation.
1267 // This happens in glibc's btowc and in some configure checks.
1268 return !isTriviallyRecursive(F);
1269 }
1270
1271 /// If the type for the method's class was generated by
1272 /// CGDebugInfo::createContextChain(), the cache contains only a
1273 /// limited DIType without any declarations. Since EmitFunctionStart()
1274 /// needs to find the canonical declaration for each method, we need
1275 /// to construct the complete type prior to emitting the method.
CompleteDIClassType(const CXXMethodDecl * D)1276 void CodeGenModule::CompleteDIClassType(const CXXMethodDecl* D) {
1277 if (!D->isInstance())
1278 return;
1279
1280 if (CGDebugInfo *DI = getModuleDebugInfo())
1281 if (getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo) {
1282 const PointerType *ThisPtr =
1283 cast<PointerType>(D->getThisType(getContext()));
1284 DI->getOrCreateRecordType(ThisPtr->getPointeeType(), D->getLocation());
1285 }
1286 }
1287
EmitGlobalDefinition(GlobalDecl GD)1288 void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD) {
1289 const ValueDecl *D = cast<ValueDecl>(GD.getDecl());
1290
1291 PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(),
1292 Context.getSourceManager(),
1293 "Generating code for declaration");
1294
1295 if (isa<FunctionDecl>(D)) {
1296 // At -O0, don't generate IR for functions with available_externally
1297 // linkage.
1298 if (!shouldEmitFunction(GD))
1299 return;
1300
1301 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
1302 CompleteDIClassType(Method);
1303 // Make sure to emit the definition(s) before we emit the thunks.
1304 // This is necessary for the generation of certain thunks.
1305 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(Method))
1306 EmitCXXConstructor(CD, GD.getCtorType());
1307 else if (const CXXDestructorDecl *DD =dyn_cast<CXXDestructorDecl>(Method))
1308 EmitCXXDestructor(DD, GD.getDtorType());
1309 else
1310 EmitGlobalFunctionDefinition(GD);
1311
1312 if (Method->isVirtual())
1313 getVTables().EmitThunks(GD);
1314
1315 return;
1316 }
1317
1318 return EmitGlobalFunctionDefinition(GD);
1319 }
1320
1321 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1322 return EmitGlobalVarDefinition(VD);
1323
1324 llvm_unreachable("Invalid argument to EmitGlobalDefinition()");
1325 }
1326
1327 /// GetOrCreateLLVMFunction - If the specified mangled name is not in the
1328 /// module, create and return an llvm Function with the specified type. If there
1329 /// is something in the module with the specified name, return it potentially
1330 /// bitcasted to the right type.
1331 ///
1332 /// If D is non-null, it specifies a decl that correspond to this. This is used
1333 /// to set the attributes on the function when it is first created.
1334 llvm::Constant *
GetOrCreateLLVMFunction(StringRef MangledName,llvm::Type * Ty,GlobalDecl GD,bool ForVTable,llvm::AttributeSet ExtraAttrs)1335 CodeGenModule::GetOrCreateLLVMFunction(StringRef MangledName,
1336 llvm::Type *Ty,
1337 GlobalDecl GD, bool ForVTable,
1338 llvm::AttributeSet ExtraAttrs) {
1339 const Decl *D = GD.getDecl();
1340
1341 // Lookup the entry, lazily creating it if necessary.
1342 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
1343 if (Entry) {
1344 if (WeakRefReferences.erase(Entry)) {
1345 const FunctionDecl *FD = cast_or_null<FunctionDecl>(D);
1346 if (FD && !FD->hasAttr<WeakAttr>())
1347 Entry->setLinkage(llvm::Function::ExternalLinkage);
1348 }
1349
1350 if (Entry->getType()->getElementType() == Ty)
1351 return Entry;
1352
1353 // Make sure the result is of the correct type.
1354 return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo());
1355 }
1356
1357 // All MSVC dtors other than the base dtor are linkonce_odr and delegate to
1358 // each other bottoming out with the base dtor. Therefore we emit non-base
1359 // dtors on usage, even if there is no dtor definition in the TU.
1360 if (D && isa<CXXDestructorDecl>(D) &&
1361 getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D),
1362 GD.getDtorType()))
1363 DeferredDeclsToEmit.push_back(GD);
1364
1365 // This function doesn't have a complete type (for example, the return
1366 // type is an incomplete struct). Use a fake type instead, and make
1367 // sure not to try to set attributes.
1368 bool IsIncompleteFunction = false;
1369
1370 llvm::FunctionType *FTy;
1371 if (isa<llvm::FunctionType>(Ty)) {
1372 FTy = cast<llvm::FunctionType>(Ty);
1373 } else {
1374 FTy = llvm::FunctionType::get(VoidTy, false);
1375 IsIncompleteFunction = true;
1376 }
1377
1378 llvm::Function *F = llvm::Function::Create(FTy,
1379 llvm::Function::ExternalLinkage,
1380 MangledName, &getModule());
1381 assert(F->getName() == MangledName && "name was uniqued!");
1382 if (D)
1383 SetFunctionAttributes(GD, F, IsIncompleteFunction);
1384 if (ExtraAttrs.hasAttributes(llvm::AttributeSet::FunctionIndex)) {
1385 llvm::AttrBuilder B(ExtraAttrs, llvm::AttributeSet::FunctionIndex);
1386 F->addAttributes(llvm::AttributeSet::FunctionIndex,
1387 llvm::AttributeSet::get(VMContext,
1388 llvm::AttributeSet::FunctionIndex,
1389 B));
1390 }
1391
1392 // This is the first use or definition of a mangled name. If there is a
1393 // deferred decl with this name, remember that we need to emit it at the end
1394 // of the file.
1395 llvm::StringMap<GlobalDecl>::iterator DDI = DeferredDecls.find(MangledName);
1396 if (DDI != DeferredDecls.end()) {
1397 // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
1398 // list, and remove it from DeferredDecls (since we don't need it anymore).
1399 DeferredDeclsToEmit.push_back(DDI->second);
1400 DeferredDecls.erase(DDI);
1401
1402 // Otherwise, there are cases we have to worry about where we're
1403 // using a declaration for which we must emit a definition but where
1404 // we might not find a top-level definition:
1405 // - member functions defined inline in their classes
1406 // - friend functions defined inline in some class
1407 // - special member functions with implicit definitions
1408 // If we ever change our AST traversal to walk into class methods,
1409 // this will be unnecessary.
1410 //
1411 // We also don't emit a definition for a function if it's going to be an entry
1412 // in a vtable, unless it's already marked as used.
1413 } else if (getLangOpts().CPlusPlus && D) {
1414 // Look for a declaration that's lexically in a record.
1415 const FunctionDecl *FD = cast<FunctionDecl>(D);
1416 FD = FD->getMostRecentDecl();
1417 do {
1418 if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
1419 if (FD->isImplicit() && !ForVTable) {
1420 assert(FD->isUsed() && "Sema didn't mark implicit function as used!");
1421 DeferredDeclsToEmit.push_back(GD.getWithDecl(FD));
1422 break;
1423 } else if (FD->doesThisDeclarationHaveABody()) {
1424 DeferredDeclsToEmit.push_back(GD.getWithDecl(FD));
1425 break;
1426 }
1427 }
1428 FD = FD->getPreviousDecl();
1429 } while (FD);
1430 }
1431
1432 // Make sure the result is of the requested type.
1433 if (!IsIncompleteFunction) {
1434 assert(F->getType()->getElementType() == Ty);
1435 return F;
1436 }
1437
1438 llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
1439 return llvm::ConstantExpr::getBitCast(F, PTy);
1440 }
1441
1442 /// GetAddrOfFunction - Return the address of the given function. If Ty is
1443 /// non-null, then this function will use the specified type if it has to
1444 /// create it (this occurs when we see a definition of the function).
GetAddrOfFunction(GlobalDecl GD,llvm::Type * Ty,bool ForVTable)1445 llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD,
1446 llvm::Type *Ty,
1447 bool ForVTable) {
1448 // If there was no specific requested type, just convert it now.
1449 if (!Ty)
1450 Ty = getTypes().ConvertType(cast<ValueDecl>(GD.getDecl())->getType());
1451
1452 StringRef MangledName = getMangledName(GD);
1453 return GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable);
1454 }
1455
1456 /// CreateRuntimeFunction - Create a new runtime function with the specified
1457 /// type and name.
1458 llvm::Constant *
CreateRuntimeFunction(llvm::FunctionType * FTy,StringRef Name,llvm::AttributeSet ExtraAttrs)1459 CodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy,
1460 StringRef Name,
1461 llvm::AttributeSet ExtraAttrs) {
1462 llvm::Constant *C
1463 = GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
1464 ExtraAttrs);
1465 if (llvm::Function *F = dyn_cast<llvm::Function>(C))
1466 if (F->empty())
1467 F->setCallingConv(getRuntimeCC());
1468 return C;
1469 }
1470
1471 /// isTypeConstant - Determine whether an object of this type can be emitted
1472 /// as a constant.
1473 ///
1474 /// If ExcludeCtor is true, the duration when the object's constructor runs
1475 /// will not be considered. The caller will need to verify that the object is
1476 /// not written to during its construction.
isTypeConstant(QualType Ty,bool ExcludeCtor)1477 bool CodeGenModule::isTypeConstant(QualType Ty, bool ExcludeCtor) {
1478 if (!Ty.isConstant(Context) && !Ty->isReferenceType())
1479 return false;
1480
1481 if (Context.getLangOpts().CPlusPlus) {
1482 if (const CXXRecordDecl *Record
1483 = Context.getBaseElementType(Ty)->getAsCXXRecordDecl())
1484 return ExcludeCtor && !Record->hasMutableFields() &&
1485 Record->hasTrivialDestructor();
1486 }
1487
1488 return true;
1489 }
1490
1491 /// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module,
1492 /// create and return an llvm GlobalVariable with the specified type. If there
1493 /// is something in the module with the specified name, return it potentially
1494 /// bitcasted to the right type.
1495 ///
1496 /// If D is non-null, it specifies a decl that correspond to this. This is used
1497 /// to set the attributes on the global when it is first created.
1498 llvm::Constant *
GetOrCreateLLVMGlobal(StringRef MangledName,llvm::PointerType * Ty,const VarDecl * D,bool UnnamedAddr)1499 CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName,
1500 llvm::PointerType *Ty,
1501 const VarDecl *D,
1502 bool UnnamedAddr) {
1503 // Lookup the entry, lazily creating it if necessary.
1504 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
1505 if (Entry) {
1506 if (WeakRefReferences.erase(Entry)) {
1507 if (D && !D->hasAttr<WeakAttr>())
1508 Entry->setLinkage(llvm::Function::ExternalLinkage);
1509 }
1510
1511 if (UnnamedAddr)
1512 Entry->setUnnamedAddr(true);
1513
1514 if (Entry->getType() == Ty)
1515 return Entry;
1516
1517 // Make sure the result is of the correct type.
1518 return llvm::ConstantExpr::getBitCast(Entry, Ty);
1519 }
1520
1521 // This is the first use or definition of a mangled name. If there is a
1522 // deferred decl with this name, remember that we need to emit it at the end
1523 // of the file.
1524 llvm::StringMap<GlobalDecl>::iterator DDI = DeferredDecls.find(MangledName);
1525 if (DDI != DeferredDecls.end()) {
1526 // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
1527 // list, and remove it from DeferredDecls (since we don't need it anymore).
1528 DeferredDeclsToEmit.push_back(DDI->second);
1529 DeferredDecls.erase(DDI);
1530 }
1531
1532 unsigned AddrSpace = GetGlobalVarAddressSpace(D, Ty->getAddressSpace());
1533 llvm::GlobalVariable *GV =
1534 new llvm::GlobalVariable(getModule(), Ty->getElementType(), false,
1535 llvm::GlobalValue::ExternalLinkage,
1536 0, MangledName, 0,
1537 llvm::GlobalVariable::NotThreadLocal, AddrSpace);
1538
1539 // Handle things which are present even on external declarations.
1540 if (D) {
1541 // FIXME: This code is overly simple and should be merged with other global
1542 // handling.
1543 GV->setConstant(isTypeConstant(D->getType(), false));
1544
1545 // Set linkage and visibility in case we never see a definition.
1546 LinkageInfo LV = D->getLinkageAndVisibility();
1547 if (LV.getLinkage() != ExternalLinkage) {
1548 // Don't set internal linkage on declarations.
1549 } else {
1550 if (D->hasAttr<DLLImportAttr>())
1551 GV->setLinkage(llvm::GlobalValue::DLLImportLinkage);
1552 else if (D->hasAttr<WeakAttr>() || D->isWeakImported())
1553 GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
1554
1555 // Set visibility on a declaration only if it's explicit.
1556 if (LV.isVisibilityExplicit())
1557 GV->setVisibility(GetLLVMVisibility(LV.getVisibility()));
1558 }
1559
1560 if (D->getTLSKind()) {
1561 if (D->getTLSKind() == VarDecl::TLS_Dynamic)
1562 CXXThreadLocals.push_back(std::make_pair(D, GV));
1563 setTLSMode(GV, *D);
1564 }
1565 }
1566
1567 if (AddrSpace != Ty->getAddressSpace())
1568 return llvm::ConstantExpr::getBitCast(GV, Ty);
1569 else
1570 return GV;
1571 }
1572
1573
1574 llvm::GlobalVariable *
CreateOrReplaceCXXRuntimeVariable(StringRef Name,llvm::Type * Ty,llvm::GlobalValue::LinkageTypes Linkage)1575 CodeGenModule::CreateOrReplaceCXXRuntimeVariable(StringRef Name,
1576 llvm::Type *Ty,
1577 llvm::GlobalValue::LinkageTypes Linkage) {
1578 llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name);
1579 llvm::GlobalVariable *OldGV = 0;
1580
1581
1582 if (GV) {
1583 // Check if the variable has the right type.
1584 if (GV->getType()->getElementType() == Ty)
1585 return GV;
1586
1587 // Because C++ name mangling, the only way we can end up with an already
1588 // existing global with the same name is if it has been declared extern "C".
1589 assert(GV->isDeclaration() && "Declaration has wrong type!");
1590 OldGV = GV;
1591 }
1592
1593 // Create a new variable.
1594 GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true,
1595 Linkage, 0, Name);
1596
1597 if (OldGV) {
1598 // Replace occurrences of the old variable if needed.
1599 GV->takeName(OldGV);
1600
1601 if (!OldGV->use_empty()) {
1602 llvm::Constant *NewPtrForOldDecl =
1603 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
1604 OldGV->replaceAllUsesWith(NewPtrForOldDecl);
1605 }
1606
1607 OldGV->eraseFromParent();
1608 }
1609
1610 return GV;
1611 }
1612
1613 /// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
1614 /// given global variable. If Ty is non-null and if the global doesn't exist,
1615 /// then it will be created with the specified type instead of whatever the
1616 /// normal requested type would be.
GetAddrOfGlobalVar(const VarDecl * D,llvm::Type * Ty)1617 llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
1618 llvm::Type *Ty) {
1619 assert(D->hasGlobalStorage() && "Not a global variable");
1620 QualType ASTTy = D->getType();
1621 if (Ty == 0)
1622 Ty = getTypes().ConvertTypeForMem(ASTTy);
1623
1624 llvm::PointerType *PTy =
1625 llvm::PointerType::get(Ty, getContext().getTargetAddressSpace(ASTTy));
1626
1627 StringRef MangledName = getMangledName(D);
1628 return GetOrCreateLLVMGlobal(MangledName, PTy, D);
1629 }
1630
1631 /// CreateRuntimeVariable - Create a new runtime global variable with the
1632 /// specified type and name.
1633 llvm::Constant *
CreateRuntimeVariable(llvm::Type * Ty,StringRef Name)1634 CodeGenModule::CreateRuntimeVariable(llvm::Type *Ty,
1635 StringRef Name) {
1636 return GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), 0,
1637 true);
1638 }
1639
EmitTentativeDefinition(const VarDecl * D)1640 void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) {
1641 assert(!D->getInit() && "Cannot emit definite definitions here!");
1642
1643 if (MayDeferGeneration(D)) {
1644 // If we have not seen a reference to this variable yet, place it
1645 // into the deferred declarations table to be emitted if needed
1646 // later.
1647 StringRef MangledName = getMangledName(D);
1648 if (!GetGlobalValue(MangledName)) {
1649 DeferredDecls[MangledName] = D;
1650 return;
1651 }
1652 }
1653
1654 // The tentative definition is the only definition.
1655 EmitGlobalVarDefinition(D);
1656 }
1657
GetTargetTypeStoreSize(llvm::Type * Ty) const1658 CharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const {
1659 return Context.toCharUnitsFromBits(
1660 TheDataLayout.getTypeStoreSizeInBits(Ty));
1661 }
1662
GetGlobalVarAddressSpace(const VarDecl * D,unsigned AddrSpace)1663 unsigned CodeGenModule::GetGlobalVarAddressSpace(const VarDecl *D,
1664 unsigned AddrSpace) {
1665 if (LangOpts.CUDA && CodeGenOpts.CUDAIsDevice) {
1666 if (D->hasAttr<CUDAConstantAttr>())
1667 AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_constant);
1668 else if (D->hasAttr<CUDASharedAttr>())
1669 AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_shared);
1670 else
1671 AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_device);
1672 }
1673
1674 return AddrSpace;
1675 }
1676
1677 template<typename SomeDecl>
MaybeHandleStaticInExternC(const SomeDecl * D,llvm::GlobalValue * GV)1678 void CodeGenModule::MaybeHandleStaticInExternC(const SomeDecl *D,
1679 llvm::GlobalValue *GV) {
1680 if (!getLangOpts().CPlusPlus)
1681 return;
1682
1683 // Must have 'used' attribute, or else inline assembly can't rely on
1684 // the name existing.
1685 if (!D->template hasAttr<UsedAttr>())
1686 return;
1687
1688 // Must have internal linkage and an ordinary name.
1689 if (!D->getIdentifier() || D->getFormalLinkage() != InternalLinkage)
1690 return;
1691
1692 // Must be in an extern "C" context. Entities declared directly within
1693 // a record are not extern "C" even if the record is in such a context.
1694 const SomeDecl *First = D->getFirstDeclaration();
1695 if (First->getDeclContext()->isRecord() || !First->isInExternCContext())
1696 return;
1697
1698 // OK, this is an internal linkage entity inside an extern "C" linkage
1699 // specification. Make a note of that so we can give it the "expected"
1700 // mangled name if nothing else is using that name.
1701 std::pair<StaticExternCMap::iterator, bool> R =
1702 StaticExternCValues.insert(std::make_pair(D->getIdentifier(), GV));
1703
1704 // If we have multiple internal linkage entities with the same name
1705 // in extern "C" regions, none of them gets that name.
1706 if (!R.second)
1707 R.first->second = 0;
1708 }
1709
EmitGlobalVarDefinition(const VarDecl * D)1710 void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) {
1711 llvm::Constant *Init = 0;
1712 QualType ASTTy = D->getType();
1713 CXXRecordDecl *RD = ASTTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
1714 bool NeedsGlobalCtor = false;
1715 bool NeedsGlobalDtor = RD && !RD->hasTrivialDestructor();
1716
1717 const VarDecl *InitDecl;
1718 const Expr *InitExpr = D->getAnyInitializer(InitDecl);
1719
1720 if (!InitExpr) {
1721 // This is a tentative definition; tentative definitions are
1722 // implicitly initialized with { 0 }.
1723 //
1724 // Note that tentative definitions are only emitted at the end of
1725 // a translation unit, so they should never have incomplete
1726 // type. In addition, EmitTentativeDefinition makes sure that we
1727 // never attempt to emit a tentative definition if a real one
1728 // exists. A use may still exists, however, so we still may need
1729 // to do a RAUW.
1730 assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type");
1731 Init = EmitNullConstant(D->getType());
1732 } else {
1733 initializedGlobalDecl = GlobalDecl(D);
1734 Init = EmitConstantInit(*InitDecl);
1735
1736 if (!Init) {
1737 QualType T = InitExpr->getType();
1738 if (D->getType()->isReferenceType())
1739 T = D->getType();
1740
1741 if (getLangOpts().CPlusPlus) {
1742 Init = EmitNullConstant(T);
1743 NeedsGlobalCtor = true;
1744 } else {
1745 ErrorUnsupported(D, "static initializer");
1746 Init = llvm::UndefValue::get(getTypes().ConvertType(T));
1747 }
1748 } else {
1749 // We don't need an initializer, so remove the entry for the delayed
1750 // initializer position (just in case this entry was delayed) if we
1751 // also don't need to register a destructor.
1752 if (getLangOpts().CPlusPlus && !NeedsGlobalDtor)
1753 DelayedCXXInitPosition.erase(D);
1754 }
1755 }
1756
1757 llvm::Type* InitType = Init->getType();
1758 llvm::Constant *Entry = GetAddrOfGlobalVar(D, InitType);
1759
1760 // Strip off a bitcast if we got one back.
1761 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
1762 assert(CE->getOpcode() == llvm::Instruction::BitCast ||
1763 // all zero index gep.
1764 CE->getOpcode() == llvm::Instruction::GetElementPtr);
1765 Entry = CE->getOperand(0);
1766 }
1767
1768 // Entry is now either a Function or GlobalVariable.
1769 llvm::GlobalVariable *GV = dyn_cast<llvm::GlobalVariable>(Entry);
1770
1771 // We have a definition after a declaration with the wrong type.
1772 // We must make a new GlobalVariable* and update everything that used OldGV
1773 // (a declaration or tentative definition) with the new GlobalVariable*
1774 // (which will be a definition).
1775 //
1776 // This happens if there is a prototype for a global (e.g.
1777 // "extern int x[];") and then a definition of a different type (e.g.
1778 // "int x[10];"). This also happens when an initializer has a different type
1779 // from the type of the global (this happens with unions).
1780 if (GV == 0 ||
1781 GV->getType()->getElementType() != InitType ||
1782 GV->getType()->getAddressSpace() !=
1783 GetGlobalVarAddressSpace(D, getContext().getTargetAddressSpace(ASTTy))) {
1784
1785 // Move the old entry aside so that we'll create a new one.
1786 Entry->setName(StringRef());
1787
1788 // Make a new global with the correct type, this is now guaranteed to work.
1789 GV = cast<llvm::GlobalVariable>(GetAddrOfGlobalVar(D, InitType));
1790
1791 // Replace all uses of the old global with the new global
1792 llvm::Constant *NewPtrForOldDecl =
1793 llvm::ConstantExpr::getBitCast(GV, Entry->getType());
1794 Entry->replaceAllUsesWith(NewPtrForOldDecl);
1795
1796 // Erase the old global, since it is no longer used.
1797 cast<llvm::GlobalValue>(Entry)->eraseFromParent();
1798 }
1799
1800 MaybeHandleStaticInExternC(D, GV);
1801
1802 if (D->hasAttr<AnnotateAttr>())
1803 AddGlobalAnnotations(D, GV);
1804
1805 GV->setInitializer(Init);
1806
1807 // If it is safe to mark the global 'constant', do so now.
1808 GV->setConstant(!NeedsGlobalCtor && !NeedsGlobalDtor &&
1809 isTypeConstant(D->getType(), true));
1810
1811 GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
1812
1813 // Set the llvm linkage type as appropriate.
1814 llvm::GlobalValue::LinkageTypes Linkage =
1815 GetLLVMLinkageVarDefinition(D, GV->isConstant());
1816 GV->setLinkage(Linkage);
1817 if (Linkage == llvm::GlobalVariable::CommonLinkage)
1818 // common vars aren't constant even if declared const.
1819 GV->setConstant(false);
1820
1821 SetCommonAttributes(D, GV);
1822
1823 // Emit the initializer function if necessary.
1824 if (NeedsGlobalCtor || NeedsGlobalDtor)
1825 EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor);
1826
1827 // If we are compiling with ASan, add metadata indicating dynamically
1828 // initialized globals.
1829 if (SanOpts.Address && NeedsGlobalCtor) {
1830 llvm::Module &M = getModule();
1831
1832 llvm::NamedMDNode *DynamicInitializers =
1833 M.getOrInsertNamedMetadata("llvm.asan.dynamically_initialized_globals");
1834 llvm::Value *GlobalToAdd[] = { GV };
1835 llvm::MDNode *ThisGlobal = llvm::MDNode::get(VMContext, GlobalToAdd);
1836 DynamicInitializers->addOperand(ThisGlobal);
1837 }
1838
1839 // Emit global variable debug information.
1840 if (CGDebugInfo *DI = getModuleDebugInfo())
1841 if (getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo)
1842 DI->EmitGlobalVariable(GV, D);
1843 }
1844
1845 llvm::GlobalValue::LinkageTypes
GetLLVMLinkageVarDefinition(const VarDecl * D,bool isConstant)1846 CodeGenModule::GetLLVMLinkageVarDefinition(const VarDecl *D, bool isConstant) {
1847 GVALinkage Linkage = getContext().GetGVALinkageForVariable(D);
1848 if (Linkage == GVA_Internal)
1849 return llvm::Function::InternalLinkage;
1850 else if (D->hasAttr<DLLImportAttr>())
1851 return llvm::Function::DLLImportLinkage;
1852 else if (D->hasAttr<DLLExportAttr>())
1853 return llvm::Function::DLLExportLinkage;
1854 else if (D->hasAttr<SelectAnyAttr>()) {
1855 // selectany symbols are externally visible, so use weak instead of
1856 // linkonce. MSVC optimizes away references to const selectany globals, so
1857 // all definitions should be the same and ODR linkage should be used.
1858 // http://msdn.microsoft.com/en-us/library/5tkz6s71.aspx
1859 return llvm::GlobalVariable::WeakODRLinkage;
1860 } else if (D->hasAttr<WeakAttr>()) {
1861 if (isConstant)
1862 return llvm::GlobalVariable::WeakODRLinkage;
1863 else
1864 return llvm::GlobalVariable::WeakAnyLinkage;
1865 } else if (Linkage == GVA_TemplateInstantiation ||
1866 Linkage == GVA_ExplicitTemplateInstantiation)
1867 return llvm::GlobalVariable::WeakODRLinkage;
1868 else if (!getLangOpts().CPlusPlus &&
1869 ((!CodeGenOpts.NoCommon && !D->getAttr<NoCommonAttr>()) ||
1870 D->getAttr<CommonAttr>()) &&
1871 !D->hasExternalStorage() && !D->getInit() &&
1872 !D->getAttr<SectionAttr>() && !D->getTLSKind() &&
1873 !D->getAttr<WeakImportAttr>()) {
1874 // Thread local vars aren't considered common linkage.
1875 return llvm::GlobalVariable::CommonLinkage;
1876 } else if (D->getTLSKind() == VarDecl::TLS_Dynamic &&
1877 getTarget().getTriple().isMacOSX())
1878 // On Darwin, the backing variable for a C++11 thread_local variable always
1879 // has internal linkage; all accesses should just be calls to the
1880 // Itanium-specified entry point, which has the normal linkage of the
1881 // variable.
1882 return llvm::GlobalValue::InternalLinkage;
1883 return llvm::GlobalVariable::ExternalLinkage;
1884 }
1885
1886 /// Replace the uses of a function that was declared with a non-proto type.
1887 /// We want to silently drop extra arguments from call sites
replaceUsesOfNonProtoConstant(llvm::Constant * old,llvm::Function * newFn)1888 static void replaceUsesOfNonProtoConstant(llvm::Constant *old,
1889 llvm::Function *newFn) {
1890 // Fast path.
1891 if (old->use_empty()) return;
1892
1893 llvm::Type *newRetTy = newFn->getReturnType();
1894 SmallVector<llvm::Value*, 4> newArgs;
1895
1896 for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end();
1897 ui != ue; ) {
1898 llvm::Value::use_iterator use = ui++; // Increment before the use is erased.
1899 llvm::User *user = *use;
1900
1901 // Recognize and replace uses of bitcasts. Most calls to
1902 // unprototyped functions will use bitcasts.
1903 if (llvm::ConstantExpr *bitcast = dyn_cast<llvm::ConstantExpr>(user)) {
1904 if (bitcast->getOpcode() == llvm::Instruction::BitCast)
1905 replaceUsesOfNonProtoConstant(bitcast, newFn);
1906 continue;
1907 }
1908
1909 // Recognize calls to the function.
1910 llvm::CallSite callSite(user);
1911 if (!callSite) continue;
1912 if (!callSite.isCallee(use)) continue;
1913
1914 // If the return types don't match exactly, then we can't
1915 // transform this call unless it's dead.
1916 if (callSite->getType() != newRetTy && !callSite->use_empty())
1917 continue;
1918
1919 // Get the call site's attribute list.
1920 SmallVector<llvm::AttributeSet, 8> newAttrs;
1921 llvm::AttributeSet oldAttrs = callSite.getAttributes();
1922
1923 // Collect any return attributes from the call.
1924 if (oldAttrs.hasAttributes(llvm::AttributeSet::ReturnIndex))
1925 newAttrs.push_back(
1926 llvm::AttributeSet::get(newFn->getContext(),
1927 oldAttrs.getRetAttributes()));
1928
1929 // If the function was passed too few arguments, don't transform.
1930 unsigned newNumArgs = newFn->arg_size();
1931 if (callSite.arg_size() < newNumArgs) continue;
1932
1933 // If extra arguments were passed, we silently drop them.
1934 // If any of the types mismatch, we don't transform.
1935 unsigned argNo = 0;
1936 bool dontTransform = false;
1937 for (llvm::Function::arg_iterator ai = newFn->arg_begin(),
1938 ae = newFn->arg_end(); ai != ae; ++ai, ++argNo) {
1939 if (callSite.getArgument(argNo)->getType() != ai->getType()) {
1940 dontTransform = true;
1941 break;
1942 }
1943
1944 // Add any parameter attributes.
1945 if (oldAttrs.hasAttributes(argNo + 1))
1946 newAttrs.
1947 push_back(llvm::
1948 AttributeSet::get(newFn->getContext(),
1949 oldAttrs.getParamAttributes(argNo + 1)));
1950 }
1951 if (dontTransform)
1952 continue;
1953
1954 if (oldAttrs.hasAttributes(llvm::AttributeSet::FunctionIndex))
1955 newAttrs.push_back(llvm::AttributeSet::get(newFn->getContext(),
1956 oldAttrs.getFnAttributes()));
1957
1958 // Okay, we can transform this. Create the new call instruction and copy
1959 // over the required information.
1960 newArgs.append(callSite.arg_begin(), callSite.arg_begin() + argNo);
1961
1962 llvm::CallSite newCall;
1963 if (callSite.isCall()) {
1964 newCall = llvm::CallInst::Create(newFn, newArgs, "",
1965 callSite.getInstruction());
1966 } else {
1967 llvm::InvokeInst *oldInvoke =
1968 cast<llvm::InvokeInst>(callSite.getInstruction());
1969 newCall = llvm::InvokeInst::Create(newFn,
1970 oldInvoke->getNormalDest(),
1971 oldInvoke->getUnwindDest(),
1972 newArgs, "",
1973 callSite.getInstruction());
1974 }
1975 newArgs.clear(); // for the next iteration
1976
1977 if (!newCall->getType()->isVoidTy())
1978 newCall->takeName(callSite.getInstruction());
1979 newCall.setAttributes(
1980 llvm::AttributeSet::get(newFn->getContext(), newAttrs));
1981 newCall.setCallingConv(callSite.getCallingConv());
1982
1983 // Finally, remove the old call, replacing any uses with the new one.
1984 if (!callSite->use_empty())
1985 callSite->replaceAllUsesWith(newCall.getInstruction());
1986
1987 // Copy debug location attached to CI.
1988 if (!callSite->getDebugLoc().isUnknown())
1989 newCall->setDebugLoc(callSite->getDebugLoc());
1990 callSite->eraseFromParent();
1991 }
1992 }
1993
1994 /// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we
1995 /// implement a function with no prototype, e.g. "int foo() {}". If there are
1996 /// existing call uses of the old function in the module, this adjusts them to
1997 /// call the new function directly.
1998 ///
1999 /// This is not just a cleanup: the always_inline pass requires direct calls to
2000 /// functions to be able to inline them. If there is a bitcast in the way, it
2001 /// won't inline them. Instcombine normally deletes these calls, but it isn't
2002 /// run at -O0.
ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue * Old,llvm::Function * NewFn)2003 static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
2004 llvm::Function *NewFn) {
2005 // If we're redefining a global as a function, don't transform it.
2006 if (!isa<llvm::Function>(Old)) return;
2007
2008 replaceUsesOfNonProtoConstant(Old, NewFn);
2009 }
2010
HandleCXXStaticMemberVarInstantiation(VarDecl * VD)2011 void CodeGenModule::HandleCXXStaticMemberVarInstantiation(VarDecl *VD) {
2012 TemplateSpecializationKind TSK = VD->getTemplateSpecializationKind();
2013 // If we have a definition, this might be a deferred decl. If the
2014 // instantiation is explicit, make sure we emit it at the end.
2015 if (VD->getDefinition() && TSK == TSK_ExplicitInstantiationDefinition)
2016 GetAddrOfGlobalVar(VD);
2017
2018 EmitTopLevelDecl(VD);
2019 }
2020
EmitGlobalFunctionDefinition(GlobalDecl GD)2021 void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD) {
2022 const FunctionDecl *D = cast<FunctionDecl>(GD.getDecl());
2023
2024 // Compute the function info and LLVM type.
2025 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
2026 llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
2027
2028 // Get or create the prototype for the function.
2029 llvm::Constant *Entry = GetAddrOfFunction(GD, Ty);
2030
2031 // Strip off a bitcast if we got one back.
2032 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
2033 assert(CE->getOpcode() == llvm::Instruction::BitCast);
2034 Entry = CE->getOperand(0);
2035 }
2036
2037
2038 if (cast<llvm::GlobalValue>(Entry)->getType()->getElementType() != Ty) {
2039 llvm::GlobalValue *OldFn = cast<llvm::GlobalValue>(Entry);
2040
2041 // If the types mismatch then we have to rewrite the definition.
2042 assert(OldFn->isDeclaration() &&
2043 "Shouldn't replace non-declaration");
2044
2045 // F is the Function* for the one with the wrong type, we must make a new
2046 // Function* and update everything that used F (a declaration) with the new
2047 // Function* (which will be a definition).
2048 //
2049 // This happens if there is a prototype for a function
2050 // (e.g. "int f()") and then a definition of a different type
2051 // (e.g. "int f(int x)"). Move the old function aside so that it
2052 // doesn't interfere with GetAddrOfFunction.
2053 OldFn->setName(StringRef());
2054 llvm::Function *NewFn = cast<llvm::Function>(GetAddrOfFunction(GD, Ty));
2055
2056 // This might be an implementation of a function without a
2057 // prototype, in which case, try to do special replacement of
2058 // calls which match the new prototype. The really key thing here
2059 // is that we also potentially drop arguments from the call site
2060 // so as to make a direct call, which makes the inliner happier
2061 // and suppresses a number of optimizer warnings (!) about
2062 // dropping arguments.
2063 if (!OldFn->use_empty()) {
2064 ReplaceUsesOfNonProtoTypeWithRealFunction(OldFn, NewFn);
2065 OldFn->removeDeadConstantUsers();
2066 }
2067
2068 // Replace uses of F with the Function we will endow with a body.
2069 if (!Entry->use_empty()) {
2070 llvm::Constant *NewPtrForOldDecl =
2071 llvm::ConstantExpr::getBitCast(NewFn, Entry->getType());
2072 Entry->replaceAllUsesWith(NewPtrForOldDecl);
2073 }
2074
2075 // Ok, delete the old function now, which is dead.
2076 OldFn->eraseFromParent();
2077
2078 Entry = NewFn;
2079 }
2080
2081 // We need to set linkage and visibility on the function before
2082 // generating code for it because various parts of IR generation
2083 // want to propagate this information down (e.g. to local static
2084 // declarations).
2085 llvm::Function *Fn = cast<llvm::Function>(Entry);
2086 setFunctionLinkage(GD, Fn);
2087
2088 // FIXME: this is redundant with part of SetFunctionDefinitionAttributes
2089 setGlobalVisibility(Fn, D);
2090
2091 MaybeHandleStaticInExternC(D, Fn);
2092
2093 CodeGenFunction(*this).GenerateCode(D, Fn, FI);
2094
2095 SetFunctionDefinitionAttributes(D, Fn);
2096 SetLLVMFunctionAttributesForDefinition(D, Fn);
2097
2098 if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
2099 AddGlobalCtor(Fn, CA->getPriority());
2100 if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
2101 AddGlobalDtor(Fn, DA->getPriority());
2102 if (D->hasAttr<AnnotateAttr>())
2103 AddGlobalAnnotations(D, Fn);
2104 }
2105
EmitAliasDefinition(GlobalDecl GD)2106 void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) {
2107 const ValueDecl *D = cast<ValueDecl>(GD.getDecl());
2108 const AliasAttr *AA = D->getAttr<AliasAttr>();
2109 assert(AA && "Not an alias?");
2110
2111 StringRef MangledName = getMangledName(GD);
2112
2113 // If there is a definition in the module, then it wins over the alias.
2114 // This is dubious, but allow it to be safe. Just ignore the alias.
2115 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
2116 if (Entry && !Entry->isDeclaration())
2117 return;
2118
2119 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
2120
2121 // Create a reference to the named value. This ensures that it is emitted
2122 // if a deferred decl.
2123 llvm::Constant *Aliasee;
2124 if (isa<llvm::FunctionType>(DeclTy))
2125 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD,
2126 /*ForVTable=*/false);
2127 else
2128 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
2129 llvm::PointerType::getUnqual(DeclTy), 0);
2130
2131 // Create the new alias itself, but don't set a name yet.
2132 llvm::GlobalValue *GA =
2133 new llvm::GlobalAlias(Aliasee->getType(),
2134 llvm::Function::ExternalLinkage,
2135 "", Aliasee, &getModule());
2136
2137 if (Entry) {
2138 assert(Entry->isDeclaration());
2139
2140 // If there is a declaration in the module, then we had an extern followed
2141 // by the alias, as in:
2142 // extern int test6();
2143 // ...
2144 // int test6() __attribute__((alias("test7")));
2145 //
2146 // Remove it and replace uses of it with the alias.
2147 GA->takeName(Entry);
2148
2149 Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
2150 Entry->getType()));
2151 Entry->eraseFromParent();
2152 } else {
2153 GA->setName(MangledName);
2154 }
2155
2156 // Set attributes which are particular to an alias; this is a
2157 // specialization of the attributes which may be set on a global
2158 // variable/function.
2159 if (D->hasAttr<DLLExportAttr>()) {
2160 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2161 // The dllexport attribute is ignored for undefined symbols.
2162 if (FD->hasBody())
2163 GA->setLinkage(llvm::Function::DLLExportLinkage);
2164 } else {
2165 GA->setLinkage(llvm::Function::DLLExportLinkage);
2166 }
2167 } else if (D->hasAttr<WeakAttr>() ||
2168 D->hasAttr<WeakRefAttr>() ||
2169 D->isWeakImported()) {
2170 GA->setLinkage(llvm::Function::WeakAnyLinkage);
2171 }
2172
2173 SetCommonAttributes(D, GA);
2174 }
2175
getIntrinsic(unsigned IID,ArrayRef<llvm::Type * > Tys)2176 llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,
2177 ArrayRef<llvm::Type*> Tys) {
2178 return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID,
2179 Tys);
2180 }
2181
2182 static llvm::StringMapEntry<llvm::Constant*> &
GetConstantCFStringEntry(llvm::StringMap<llvm::Constant * > & Map,const StringLiteral * Literal,bool TargetIsLSB,bool & IsUTF16,unsigned & StringLength)2183 GetConstantCFStringEntry(llvm::StringMap<llvm::Constant*> &Map,
2184 const StringLiteral *Literal,
2185 bool TargetIsLSB,
2186 bool &IsUTF16,
2187 unsigned &StringLength) {
2188 StringRef String = Literal->getString();
2189 unsigned NumBytes = String.size();
2190
2191 // Check for simple case.
2192 if (!Literal->containsNonAsciiOrNull()) {
2193 StringLength = NumBytes;
2194 return Map.GetOrCreateValue(String);
2195 }
2196
2197 // Otherwise, convert the UTF8 literals into a string of shorts.
2198 IsUTF16 = true;
2199
2200 SmallVector<UTF16, 128> ToBuf(NumBytes + 1); // +1 for ending nulls.
2201 const UTF8 *FromPtr = (const UTF8 *)String.data();
2202 UTF16 *ToPtr = &ToBuf[0];
2203
2204 (void)ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
2205 &ToPtr, ToPtr + NumBytes,
2206 strictConversion);
2207
2208 // ConvertUTF8toUTF16 returns the length in ToPtr.
2209 StringLength = ToPtr - &ToBuf[0];
2210
2211 // Add an explicit null.
2212 *ToPtr = 0;
2213 return Map.
2214 GetOrCreateValue(StringRef(reinterpret_cast<const char *>(ToBuf.data()),
2215 (StringLength + 1) * 2));
2216 }
2217
2218 static llvm::StringMapEntry<llvm::Constant*> &
GetConstantStringEntry(llvm::StringMap<llvm::Constant * > & Map,const StringLiteral * Literal,unsigned & StringLength)2219 GetConstantStringEntry(llvm::StringMap<llvm::Constant*> &Map,
2220 const StringLiteral *Literal,
2221 unsigned &StringLength) {
2222 StringRef String = Literal->getString();
2223 StringLength = String.size();
2224 return Map.GetOrCreateValue(String);
2225 }
2226
2227 llvm::Constant *
GetAddrOfConstantCFString(const StringLiteral * Literal)2228 CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) {
2229 unsigned StringLength = 0;
2230 bool isUTF16 = false;
2231 llvm::StringMapEntry<llvm::Constant*> &Entry =
2232 GetConstantCFStringEntry(CFConstantStringMap, Literal,
2233 getDataLayout().isLittleEndian(),
2234 isUTF16, StringLength);
2235
2236 if (llvm::Constant *C = Entry.getValue())
2237 return C;
2238
2239 llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
2240 llvm::Constant *Zeros[] = { Zero, Zero };
2241 llvm::Value *V;
2242
2243 // If we don't already have it, get __CFConstantStringClassReference.
2244 if (!CFConstantStringClassRef) {
2245 llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
2246 Ty = llvm::ArrayType::get(Ty, 0);
2247 llvm::Constant *GV = CreateRuntimeVariable(Ty,
2248 "__CFConstantStringClassReference");
2249 // Decay array -> ptr
2250 V = llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
2251 CFConstantStringClassRef = V;
2252 }
2253 else
2254 V = CFConstantStringClassRef;
2255
2256 QualType CFTy = getContext().getCFConstantStringType();
2257
2258 llvm::StructType *STy =
2259 cast<llvm::StructType>(getTypes().ConvertType(CFTy));
2260
2261 llvm::Constant *Fields[4];
2262
2263 // Class pointer.
2264 Fields[0] = cast<llvm::ConstantExpr>(V);
2265
2266 // Flags.
2267 llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
2268 Fields[1] = isUTF16 ? llvm::ConstantInt::get(Ty, 0x07d0) :
2269 llvm::ConstantInt::get(Ty, 0x07C8);
2270
2271 // String pointer.
2272 llvm::Constant *C = 0;
2273 if (isUTF16) {
2274 ArrayRef<uint16_t> Arr =
2275 llvm::makeArrayRef<uint16_t>(reinterpret_cast<uint16_t*>(
2276 const_cast<char *>(Entry.getKey().data())),
2277 Entry.getKey().size() / 2);
2278 C = llvm::ConstantDataArray::get(VMContext, Arr);
2279 } else {
2280 C = llvm::ConstantDataArray::getString(VMContext, Entry.getKey());
2281 }
2282
2283 llvm::GlobalValue::LinkageTypes Linkage;
2284 if (isUTF16)
2285 // FIXME: why do utf strings get "_" labels instead of "L" labels?
2286 Linkage = llvm::GlobalValue::InternalLinkage;
2287 else
2288 // FIXME: With OS X ld 123.2 (xcode 4) and LTO we would get a linker error
2289 // when using private linkage. It is not clear if this is a bug in ld
2290 // or a reasonable new restriction.
2291 Linkage = llvm::GlobalValue::LinkerPrivateLinkage;
2292
2293 // Note: -fwritable-strings doesn't make the backing store strings of
2294 // CFStrings writable. (See <rdar://problem/10657500>)
2295 llvm::GlobalVariable *GV =
2296 new llvm::GlobalVariable(getModule(), C->getType(), /*isConstant=*/true,
2297 Linkage, C, ".str");
2298 GV->setUnnamedAddr(true);
2299 // Don't enforce the target's minimum global alignment, since the only use
2300 // of the string is via this class initializer.
2301 if (isUTF16) {
2302 CharUnits Align = getContext().getTypeAlignInChars(getContext().ShortTy);
2303 GV->setAlignment(Align.getQuantity());
2304 } else {
2305 CharUnits Align = getContext().getTypeAlignInChars(getContext().CharTy);
2306 GV->setAlignment(Align.getQuantity());
2307 }
2308
2309 // String.
2310 Fields[2] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
2311
2312 if (isUTF16)
2313 // Cast the UTF16 string to the correct type.
2314 Fields[2] = llvm::ConstantExpr::getBitCast(Fields[2], Int8PtrTy);
2315
2316 // String length.
2317 Ty = getTypes().ConvertType(getContext().LongTy);
2318 Fields[3] = llvm::ConstantInt::get(Ty, StringLength);
2319
2320 // The struct.
2321 C = llvm::ConstantStruct::get(STy, Fields);
2322 GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
2323 llvm::GlobalVariable::PrivateLinkage, C,
2324 "_unnamed_cfstring_");
2325 if (const char *Sect = getTarget().getCFStringSection())
2326 GV->setSection(Sect);
2327 Entry.setValue(GV);
2328
2329 return GV;
2330 }
2331
2332 static RecordDecl *
CreateRecordDecl(const ASTContext & Ctx,RecordDecl::TagKind TK,DeclContext * DC,IdentifierInfo * Id)2333 CreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK,
2334 DeclContext *DC, IdentifierInfo *Id) {
2335 SourceLocation Loc;
2336 if (Ctx.getLangOpts().CPlusPlus)
2337 return CXXRecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
2338 else
2339 return RecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
2340 }
2341
2342 llvm::Constant *
GetAddrOfConstantString(const StringLiteral * Literal)2343 CodeGenModule::GetAddrOfConstantString(const StringLiteral *Literal) {
2344 unsigned StringLength = 0;
2345 llvm::StringMapEntry<llvm::Constant*> &Entry =
2346 GetConstantStringEntry(CFConstantStringMap, Literal, StringLength);
2347
2348 if (llvm::Constant *C = Entry.getValue())
2349 return C;
2350
2351 llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
2352 llvm::Constant *Zeros[] = { Zero, Zero };
2353 llvm::Value *V;
2354 // If we don't already have it, get _NSConstantStringClassReference.
2355 if (!ConstantStringClassRef) {
2356 std::string StringClass(getLangOpts().ObjCConstantStringClass);
2357 llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
2358 llvm::Constant *GV;
2359 if (LangOpts.ObjCRuntime.isNonFragile()) {
2360 std::string str =
2361 StringClass.empty() ? "OBJC_CLASS_$_NSConstantString"
2362 : "OBJC_CLASS_$_" + StringClass;
2363 GV = getObjCRuntime().GetClassGlobal(str);
2364 // Make sure the result is of the correct type.
2365 llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
2366 V = llvm::ConstantExpr::getBitCast(GV, PTy);
2367 ConstantStringClassRef = V;
2368 } else {
2369 std::string str =
2370 StringClass.empty() ? "_NSConstantStringClassReference"
2371 : "_" + StringClass + "ClassReference";
2372 llvm::Type *PTy = llvm::ArrayType::get(Ty, 0);
2373 GV = CreateRuntimeVariable(PTy, str);
2374 // Decay array -> ptr
2375 V = llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
2376 ConstantStringClassRef = V;
2377 }
2378 }
2379 else
2380 V = ConstantStringClassRef;
2381
2382 if (!NSConstantStringType) {
2383 // Construct the type for a constant NSString.
2384 RecordDecl *D = CreateRecordDecl(Context, TTK_Struct,
2385 Context.getTranslationUnitDecl(),
2386 &Context.Idents.get("__builtin_NSString"));
2387 D->startDefinition();
2388
2389 QualType FieldTypes[3];
2390
2391 // const int *isa;
2392 FieldTypes[0] = Context.getPointerType(Context.IntTy.withConst());
2393 // const char *str;
2394 FieldTypes[1] = Context.getPointerType(Context.CharTy.withConst());
2395 // unsigned int length;
2396 FieldTypes[2] = Context.UnsignedIntTy;
2397
2398 // Create fields
2399 for (unsigned i = 0; i < 3; ++i) {
2400 FieldDecl *Field = FieldDecl::Create(Context, D,
2401 SourceLocation(),
2402 SourceLocation(), 0,
2403 FieldTypes[i], /*TInfo=*/0,
2404 /*BitWidth=*/0,
2405 /*Mutable=*/false,
2406 ICIS_NoInit);
2407 Field->setAccess(AS_public);
2408 D->addDecl(Field);
2409 }
2410
2411 D->completeDefinition();
2412 QualType NSTy = Context.getTagDeclType(D);
2413 NSConstantStringType = cast<llvm::StructType>(getTypes().ConvertType(NSTy));
2414 }
2415
2416 llvm::Constant *Fields[3];
2417
2418 // Class pointer.
2419 Fields[0] = cast<llvm::ConstantExpr>(V);
2420
2421 // String pointer.
2422 llvm::Constant *C =
2423 llvm::ConstantDataArray::getString(VMContext, Entry.getKey());
2424
2425 llvm::GlobalValue::LinkageTypes Linkage;
2426 bool isConstant;
2427 Linkage = llvm::GlobalValue::PrivateLinkage;
2428 isConstant = !LangOpts.WritableStrings;
2429
2430 llvm::GlobalVariable *GV =
2431 new llvm::GlobalVariable(getModule(), C->getType(), isConstant, Linkage, C,
2432 ".str");
2433 GV->setUnnamedAddr(true);
2434 // Don't enforce the target's minimum global alignment, since the only use
2435 // of the string is via this class initializer.
2436 CharUnits Align = getContext().getTypeAlignInChars(getContext().CharTy);
2437 GV->setAlignment(Align.getQuantity());
2438 Fields[1] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
2439
2440 // String length.
2441 llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
2442 Fields[2] = llvm::ConstantInt::get(Ty, StringLength);
2443
2444 // The struct.
2445 C = llvm::ConstantStruct::get(NSConstantStringType, Fields);
2446 GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
2447 llvm::GlobalVariable::PrivateLinkage, C,
2448 "_unnamed_nsstring_");
2449 // FIXME. Fix section.
2450 if (const char *Sect =
2451 LangOpts.ObjCRuntime.isNonFragile()
2452 ? getTarget().getNSStringNonFragileABISection()
2453 : getTarget().getNSStringSection())
2454 GV->setSection(Sect);
2455 Entry.setValue(GV);
2456
2457 return GV;
2458 }
2459
getObjCFastEnumerationStateType()2460 QualType CodeGenModule::getObjCFastEnumerationStateType() {
2461 if (ObjCFastEnumerationStateType.isNull()) {
2462 RecordDecl *D = CreateRecordDecl(Context, TTK_Struct,
2463 Context.getTranslationUnitDecl(),
2464 &Context.Idents.get("__objcFastEnumerationState"));
2465 D->startDefinition();
2466
2467 QualType FieldTypes[] = {
2468 Context.UnsignedLongTy,
2469 Context.getPointerType(Context.getObjCIdType()),
2470 Context.getPointerType(Context.UnsignedLongTy),
2471 Context.getConstantArrayType(Context.UnsignedLongTy,
2472 llvm::APInt(32, 5), ArrayType::Normal, 0)
2473 };
2474
2475 for (size_t i = 0; i < 4; ++i) {
2476 FieldDecl *Field = FieldDecl::Create(Context,
2477 D,
2478 SourceLocation(),
2479 SourceLocation(), 0,
2480 FieldTypes[i], /*TInfo=*/0,
2481 /*BitWidth=*/0,
2482 /*Mutable=*/false,
2483 ICIS_NoInit);
2484 Field->setAccess(AS_public);
2485 D->addDecl(Field);
2486 }
2487
2488 D->completeDefinition();
2489 ObjCFastEnumerationStateType = Context.getTagDeclType(D);
2490 }
2491
2492 return ObjCFastEnumerationStateType;
2493 }
2494
2495 llvm::Constant *
GetConstantArrayFromStringLiteral(const StringLiteral * E)2496 CodeGenModule::GetConstantArrayFromStringLiteral(const StringLiteral *E) {
2497 assert(!E->getType()->isPointerType() && "Strings are always arrays");
2498
2499 // Don't emit it as the address of the string, emit the string data itself
2500 // as an inline array.
2501 if (E->getCharByteWidth() == 1) {
2502 SmallString<64> Str(E->getString());
2503
2504 // Resize the string to the right size, which is indicated by its type.
2505 const ConstantArrayType *CAT = Context.getAsConstantArrayType(E->getType());
2506 Str.resize(CAT->getSize().getZExtValue());
2507 return llvm::ConstantDataArray::getString(VMContext, Str, false);
2508 }
2509
2510 llvm::ArrayType *AType =
2511 cast<llvm::ArrayType>(getTypes().ConvertType(E->getType()));
2512 llvm::Type *ElemTy = AType->getElementType();
2513 unsigned NumElements = AType->getNumElements();
2514
2515 // Wide strings have either 2-byte or 4-byte elements.
2516 if (ElemTy->getPrimitiveSizeInBits() == 16) {
2517 SmallVector<uint16_t, 32> Elements;
2518 Elements.reserve(NumElements);
2519
2520 for(unsigned i = 0, e = E->getLength(); i != e; ++i)
2521 Elements.push_back(E->getCodeUnit(i));
2522 Elements.resize(NumElements);
2523 return llvm::ConstantDataArray::get(VMContext, Elements);
2524 }
2525
2526 assert(ElemTy->getPrimitiveSizeInBits() == 32);
2527 SmallVector<uint32_t, 32> Elements;
2528 Elements.reserve(NumElements);
2529
2530 for(unsigned i = 0, e = E->getLength(); i != e; ++i)
2531 Elements.push_back(E->getCodeUnit(i));
2532 Elements.resize(NumElements);
2533 return llvm::ConstantDataArray::get(VMContext, Elements);
2534 }
2535
2536 /// GetAddrOfConstantStringFromLiteral - Return a pointer to a
2537 /// constant array for the given string literal.
2538 llvm::Constant *
GetAddrOfConstantStringFromLiteral(const StringLiteral * S)2539 CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S) {
2540 CharUnits Align = getContext().getAlignOfGlobalVarInChars(S->getType());
2541 if (S->isAscii() || S->isUTF8()) {
2542 SmallString<64> Str(S->getString());
2543
2544 // Resize the string to the right size, which is indicated by its type.
2545 const ConstantArrayType *CAT = Context.getAsConstantArrayType(S->getType());
2546 Str.resize(CAT->getSize().getZExtValue());
2547 return GetAddrOfConstantString(Str, /*GlobalName*/ 0, Align.getQuantity());
2548 }
2549
2550 // FIXME: the following does not memoize wide strings.
2551 llvm::Constant *C = GetConstantArrayFromStringLiteral(S);
2552 llvm::GlobalVariable *GV =
2553 new llvm::GlobalVariable(getModule(),C->getType(),
2554 !LangOpts.WritableStrings,
2555 llvm::GlobalValue::PrivateLinkage,
2556 C,".str");
2557
2558 GV->setAlignment(Align.getQuantity());
2559 GV->setUnnamedAddr(true);
2560 return GV;
2561 }
2562
2563 /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
2564 /// array for the given ObjCEncodeExpr node.
2565 llvm::Constant *
GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr * E)2566 CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
2567 std::string Str;
2568 getContext().getObjCEncodingForType(E->getEncodedType(), Str);
2569
2570 return GetAddrOfConstantCString(Str);
2571 }
2572
2573
2574 /// GenerateWritableString -- Creates storage for a string literal.
GenerateStringLiteral(StringRef str,bool constant,CodeGenModule & CGM,const char * GlobalName,unsigned Alignment)2575 static llvm::GlobalVariable *GenerateStringLiteral(StringRef str,
2576 bool constant,
2577 CodeGenModule &CGM,
2578 const char *GlobalName,
2579 unsigned Alignment) {
2580 // Create Constant for this string literal. Don't add a '\0'.
2581 llvm::Constant *C =
2582 llvm::ConstantDataArray::getString(CGM.getLLVMContext(), str, false);
2583
2584 // Create a global variable for this string
2585 llvm::GlobalVariable *GV =
2586 new llvm::GlobalVariable(CGM.getModule(), C->getType(), constant,
2587 llvm::GlobalValue::PrivateLinkage,
2588 C, GlobalName);
2589 GV->setAlignment(Alignment);
2590 GV->setUnnamedAddr(true);
2591 return GV;
2592 }
2593
2594 /// GetAddrOfConstantString - Returns a pointer to a character array
2595 /// containing the literal. This contents are exactly that of the
2596 /// given string, i.e. it will not be null terminated automatically;
2597 /// see GetAddrOfConstantCString. Note that whether the result is
2598 /// actually a pointer to an LLVM constant depends on
2599 /// Feature.WriteableStrings.
2600 ///
2601 /// The result has pointer to array type.
GetAddrOfConstantString(StringRef Str,const char * GlobalName,unsigned Alignment)2602 llvm::Constant *CodeGenModule::GetAddrOfConstantString(StringRef Str,
2603 const char *GlobalName,
2604 unsigned Alignment) {
2605 // Get the default prefix if a name wasn't specified.
2606 if (!GlobalName)
2607 GlobalName = ".str";
2608
2609 if (Alignment == 0)
2610 Alignment = getContext().getAlignOfGlobalVarInChars(getContext().CharTy)
2611 .getQuantity();
2612
2613 // Don't share any string literals if strings aren't constant.
2614 if (LangOpts.WritableStrings)
2615 return GenerateStringLiteral(Str, false, *this, GlobalName, Alignment);
2616
2617 llvm::StringMapEntry<llvm::GlobalVariable *> &Entry =
2618 ConstantStringMap.GetOrCreateValue(Str);
2619
2620 if (llvm::GlobalVariable *GV = Entry.getValue()) {
2621 if (Alignment > GV->getAlignment()) {
2622 GV->setAlignment(Alignment);
2623 }
2624 return GV;
2625 }
2626
2627 // Create a global variable for this.
2628 llvm::GlobalVariable *GV = GenerateStringLiteral(Str, true, *this, GlobalName,
2629 Alignment);
2630 Entry.setValue(GV);
2631 return GV;
2632 }
2633
2634 /// GetAddrOfConstantCString - Returns a pointer to a character
2635 /// array containing the literal and a terminating '\0'
2636 /// character. The result has pointer to array type.
GetAddrOfConstantCString(const std::string & Str,const char * GlobalName,unsigned Alignment)2637 llvm::Constant *CodeGenModule::GetAddrOfConstantCString(const std::string &Str,
2638 const char *GlobalName,
2639 unsigned Alignment) {
2640 StringRef StrWithNull(Str.c_str(), Str.size() + 1);
2641 return GetAddrOfConstantString(StrWithNull, GlobalName, Alignment);
2642 }
2643
GetAddrOfGlobalTemporary(const MaterializeTemporaryExpr * E,const Expr * Init)2644 llvm::Constant *CodeGenModule::GetAddrOfGlobalTemporary(
2645 const MaterializeTemporaryExpr *E, const Expr *Init) {
2646 assert((E->getStorageDuration() == SD_Static ||
2647 E->getStorageDuration() == SD_Thread) && "not a global temporary");
2648 const VarDecl *VD = cast<VarDecl>(E->getExtendingDecl());
2649
2650 // If we're not materializing a subobject of the temporary, keep the
2651 // cv-qualifiers from the type of the MaterializeTemporaryExpr.
2652 QualType MaterializedType = Init->getType();
2653 if (Init == E->GetTemporaryExpr())
2654 MaterializedType = E->getType();
2655
2656 llvm::Constant *&Slot = MaterializedGlobalTemporaryMap[E];
2657 if (Slot)
2658 return Slot;
2659
2660 // FIXME: If an externally-visible declaration extends multiple temporaries,
2661 // we need to give each temporary the same name in every translation unit (and
2662 // we also need to make the temporaries externally-visible).
2663 SmallString<256> Name;
2664 llvm::raw_svector_ostream Out(Name);
2665 getCXXABI().getMangleContext().mangleReferenceTemporary(VD, Out);
2666 Out.flush();
2667
2668 APValue *Value = 0;
2669 if (E->getStorageDuration() == SD_Static) {
2670 // We might have a cached constant initializer for this temporary. Note
2671 // that this might have a different value from the value computed by
2672 // evaluating the initializer if the surrounding constant expression
2673 // modifies the temporary.
2674 Value = getContext().getMaterializedTemporaryValue(E, false);
2675 if (Value && Value->isUninit())
2676 Value = 0;
2677 }
2678
2679 // Try evaluating it now, it might have a constant initializer.
2680 Expr::EvalResult EvalResult;
2681 if (!Value && Init->EvaluateAsRValue(EvalResult, getContext()) &&
2682 !EvalResult.hasSideEffects())
2683 Value = &EvalResult.Val;
2684
2685 llvm::Constant *InitialValue = 0;
2686 bool Constant = false;
2687 llvm::Type *Type;
2688 if (Value) {
2689 // The temporary has a constant initializer, use it.
2690 InitialValue = EmitConstantValue(*Value, MaterializedType, 0);
2691 Constant = isTypeConstant(MaterializedType, /*ExcludeCtor*/Value);
2692 Type = InitialValue->getType();
2693 } else {
2694 // No initializer, the initialization will be provided when we
2695 // initialize the declaration which performed lifetime extension.
2696 Type = getTypes().ConvertTypeForMem(MaterializedType);
2697 }
2698
2699 // Create a global variable for this lifetime-extended temporary.
2700 llvm::GlobalVariable *GV =
2701 new llvm::GlobalVariable(getModule(), Type, Constant,
2702 llvm::GlobalValue::PrivateLinkage,
2703 InitialValue, Name.c_str());
2704 GV->setAlignment(
2705 getContext().getTypeAlignInChars(MaterializedType).getQuantity());
2706 if (VD->getTLSKind())
2707 setTLSMode(GV, *VD);
2708 Slot = GV;
2709 return GV;
2710 }
2711
2712 /// EmitObjCPropertyImplementations - Emit information for synthesized
2713 /// properties for an implementation.
EmitObjCPropertyImplementations(const ObjCImplementationDecl * D)2714 void CodeGenModule::EmitObjCPropertyImplementations(const
2715 ObjCImplementationDecl *D) {
2716 for (ObjCImplementationDecl::propimpl_iterator
2717 i = D->propimpl_begin(), e = D->propimpl_end(); i != e; ++i) {
2718 ObjCPropertyImplDecl *PID = *i;
2719
2720 // Dynamic is just for type-checking.
2721 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
2722 ObjCPropertyDecl *PD = PID->getPropertyDecl();
2723
2724 // Determine which methods need to be implemented, some may have
2725 // been overridden. Note that ::isPropertyAccessor is not the method
2726 // we want, that just indicates if the decl came from a
2727 // property. What we want to know is if the method is defined in
2728 // this implementation.
2729 if (!D->getInstanceMethod(PD->getGetterName()))
2730 CodeGenFunction(*this).GenerateObjCGetter(
2731 const_cast<ObjCImplementationDecl *>(D), PID);
2732 if (!PD->isReadOnly() &&
2733 !D->getInstanceMethod(PD->getSetterName()))
2734 CodeGenFunction(*this).GenerateObjCSetter(
2735 const_cast<ObjCImplementationDecl *>(D), PID);
2736 }
2737 }
2738 }
2739
needsDestructMethod(ObjCImplementationDecl * impl)2740 static bool needsDestructMethod(ObjCImplementationDecl *impl) {
2741 const ObjCInterfaceDecl *iface = impl->getClassInterface();
2742 for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
2743 ivar; ivar = ivar->getNextIvar())
2744 if (ivar->getType().isDestructedType())
2745 return true;
2746
2747 return false;
2748 }
2749
2750 /// EmitObjCIvarInitializations - Emit information for ivar initialization
2751 /// for an implementation.
EmitObjCIvarInitializations(ObjCImplementationDecl * D)2752 void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) {
2753 // We might need a .cxx_destruct even if we don't have any ivar initializers.
2754 if (needsDestructMethod(D)) {
2755 IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct");
2756 Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
2757 ObjCMethodDecl *DTORMethod =
2758 ObjCMethodDecl::Create(getContext(), D->getLocation(), D->getLocation(),
2759 cxxSelector, getContext().VoidTy, 0, D,
2760 /*isInstance=*/true, /*isVariadic=*/false,
2761 /*isPropertyAccessor=*/true, /*isImplicitlyDeclared=*/true,
2762 /*isDefined=*/false, ObjCMethodDecl::Required);
2763 D->addInstanceMethod(DTORMethod);
2764 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false);
2765 D->setHasDestructors(true);
2766 }
2767
2768 // If the implementation doesn't have any ivar initializers, we don't need
2769 // a .cxx_construct.
2770 if (D->getNumIvarInitializers() == 0)
2771 return;
2772
2773 IdentifierInfo *II = &getContext().Idents.get(".cxx_construct");
2774 Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
2775 // The constructor returns 'self'.
2776 ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(getContext(),
2777 D->getLocation(),
2778 D->getLocation(),
2779 cxxSelector,
2780 getContext().getObjCIdType(), 0,
2781 D, /*isInstance=*/true,
2782 /*isVariadic=*/false,
2783 /*isPropertyAccessor=*/true,
2784 /*isImplicitlyDeclared=*/true,
2785 /*isDefined=*/false,
2786 ObjCMethodDecl::Required);
2787 D->addInstanceMethod(CTORMethod);
2788 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true);
2789 D->setHasNonZeroConstructors(true);
2790 }
2791
2792 /// EmitNamespace - Emit all declarations in a namespace.
EmitNamespace(const NamespaceDecl * ND)2793 void CodeGenModule::EmitNamespace(const NamespaceDecl *ND) {
2794 for (RecordDecl::decl_iterator I = ND->decls_begin(), E = ND->decls_end();
2795 I != E; ++I)
2796 EmitTopLevelDecl(*I);
2797 }
2798
2799 // EmitLinkageSpec - Emit all declarations in a linkage spec.
EmitLinkageSpec(const LinkageSpecDecl * LSD)2800 void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) {
2801 if (LSD->getLanguage() != LinkageSpecDecl::lang_c &&
2802 LSD->getLanguage() != LinkageSpecDecl::lang_cxx) {
2803 ErrorUnsupported(LSD, "linkage spec");
2804 return;
2805 }
2806
2807 for (RecordDecl::decl_iterator I = LSD->decls_begin(), E = LSD->decls_end();
2808 I != E; ++I) {
2809 // Meta-data for ObjC class includes references to implemented methods.
2810 // Generate class's method definitions first.
2811 if (ObjCImplDecl *OID = dyn_cast<ObjCImplDecl>(*I)) {
2812 for (ObjCContainerDecl::method_iterator M = OID->meth_begin(),
2813 MEnd = OID->meth_end();
2814 M != MEnd; ++M)
2815 EmitTopLevelDecl(*M);
2816 }
2817 EmitTopLevelDecl(*I);
2818 }
2819 }
2820
2821 /// EmitTopLevelDecl - Emit code for a single top level declaration.
EmitTopLevelDecl(Decl * D)2822 void CodeGenModule::EmitTopLevelDecl(Decl *D) {
2823 // If an error has occurred, stop code generation, but continue
2824 // parsing and semantic analysis (to ensure all warnings and errors
2825 // are emitted).
2826 if (Diags.hasErrorOccurred())
2827 return;
2828
2829 // Ignore dependent declarations.
2830 if (D->getDeclContext() && D->getDeclContext()->isDependentContext())
2831 return;
2832
2833 switch (D->getKind()) {
2834 case Decl::CXXConversion:
2835 case Decl::CXXMethod:
2836 case Decl::Function:
2837 // Skip function templates
2838 if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
2839 cast<FunctionDecl>(D)->isLateTemplateParsed())
2840 return;
2841
2842 EmitGlobal(cast<FunctionDecl>(D));
2843 break;
2844
2845 case Decl::Var:
2846 // Skip variable templates
2847 if (cast<VarDecl>(D)->getDescribedVarTemplate())
2848 return;
2849 case Decl::VarTemplateSpecialization:
2850 EmitGlobal(cast<VarDecl>(D));
2851 break;
2852
2853 // Indirect fields from global anonymous structs and unions can be
2854 // ignored; only the actual variable requires IR gen support.
2855 case Decl::IndirectField:
2856 break;
2857
2858 // C++ Decls
2859 case Decl::Namespace:
2860 EmitNamespace(cast<NamespaceDecl>(D));
2861 break;
2862 // No code generation needed.
2863 case Decl::UsingShadow:
2864 case Decl::Using:
2865 case Decl::ClassTemplate:
2866 case Decl::VarTemplate:
2867 case Decl::VarTemplatePartialSpecialization:
2868 case Decl::FunctionTemplate:
2869 case Decl::TypeAliasTemplate:
2870 case Decl::Block:
2871 case Decl::Empty:
2872 break;
2873 case Decl::NamespaceAlias:
2874 if (CGDebugInfo *DI = getModuleDebugInfo())
2875 DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(*D));
2876 return;
2877 case Decl::UsingDirective: // using namespace X; [C++]
2878 if (CGDebugInfo *DI = getModuleDebugInfo())
2879 DI->EmitUsingDirective(cast<UsingDirectiveDecl>(*D));
2880 return;
2881 case Decl::CXXConstructor:
2882 // Skip function templates
2883 if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
2884 cast<FunctionDecl>(D)->isLateTemplateParsed())
2885 return;
2886
2887 getCXXABI().EmitCXXConstructors(cast<CXXConstructorDecl>(D));
2888 break;
2889 case Decl::CXXDestructor:
2890 if (cast<FunctionDecl>(D)->isLateTemplateParsed())
2891 return;
2892 getCXXABI().EmitCXXDestructors(cast<CXXDestructorDecl>(D));
2893 break;
2894
2895 case Decl::StaticAssert:
2896 // Nothing to do.
2897 break;
2898
2899 // Objective-C Decls
2900
2901 // Forward declarations, no (immediate) code generation.
2902 case Decl::ObjCInterface:
2903 case Decl::ObjCCategory:
2904 break;
2905
2906 case Decl::ObjCProtocol: {
2907 ObjCProtocolDecl *Proto = cast<ObjCProtocolDecl>(D);
2908 if (Proto->isThisDeclarationADefinition())
2909 ObjCRuntime->GenerateProtocol(Proto);
2910 break;
2911 }
2912
2913 case Decl::ObjCCategoryImpl:
2914 // Categories have properties but don't support synthesize so we
2915 // can ignore them here.
2916 ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
2917 break;
2918
2919 case Decl::ObjCImplementation: {
2920 ObjCImplementationDecl *OMD = cast<ObjCImplementationDecl>(D);
2921 EmitObjCPropertyImplementations(OMD);
2922 EmitObjCIvarInitializations(OMD);
2923 ObjCRuntime->GenerateClass(OMD);
2924 // Emit global variable debug information.
2925 if (CGDebugInfo *DI = getModuleDebugInfo())
2926 if (getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo)
2927 DI->getOrCreateInterfaceType(getContext().getObjCInterfaceType(
2928 OMD->getClassInterface()), OMD->getLocation());
2929 break;
2930 }
2931 case Decl::ObjCMethod: {
2932 ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(D);
2933 // If this is not a prototype, emit the body.
2934 if (OMD->getBody())
2935 CodeGenFunction(*this).GenerateObjCMethod(OMD);
2936 break;
2937 }
2938 case Decl::ObjCCompatibleAlias:
2939 ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D));
2940 break;
2941
2942 case Decl::LinkageSpec:
2943 EmitLinkageSpec(cast<LinkageSpecDecl>(D));
2944 break;
2945
2946 case Decl::FileScopeAsm: {
2947 FileScopeAsmDecl *AD = cast<FileScopeAsmDecl>(D);
2948 StringRef AsmString = AD->getAsmString()->getString();
2949
2950 const std::string &S = getModule().getModuleInlineAsm();
2951 if (S.empty())
2952 getModule().setModuleInlineAsm(AsmString);
2953 else if (S.end()[-1] == '\n')
2954 getModule().setModuleInlineAsm(S + AsmString.str());
2955 else
2956 getModule().setModuleInlineAsm(S + '\n' + AsmString.str());
2957 break;
2958 }
2959
2960 case Decl::Import: {
2961 ImportDecl *Import = cast<ImportDecl>(D);
2962
2963 // Ignore import declarations that come from imported modules.
2964 if (clang::Module *Owner = Import->getOwningModule()) {
2965 if (getLangOpts().CurrentModule.empty() ||
2966 Owner->getTopLevelModule()->Name == getLangOpts().CurrentModule)
2967 break;
2968 }
2969
2970 ImportedModules.insert(Import->getImportedModule());
2971 break;
2972 }
2973
2974 default:
2975 // Make sure we handled everything we should, every other kind is a
2976 // non-top-level decl. FIXME: Would be nice to have an isTopLevelDeclKind
2977 // function. Need to recode Decl::Kind to do that easily.
2978 assert(isa<TypeDecl>(D) && "Unsupported decl kind");
2979 }
2980 }
2981
2982 /// Turns the given pointer into a constant.
GetPointerConstant(llvm::LLVMContext & Context,const void * Ptr)2983 static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context,
2984 const void *Ptr) {
2985 uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr);
2986 llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
2987 return llvm::ConstantInt::get(i64, PtrInt);
2988 }
2989
EmitGlobalDeclMetadata(CodeGenModule & CGM,llvm::NamedMDNode * & GlobalMetadata,GlobalDecl D,llvm::GlobalValue * Addr)2990 static void EmitGlobalDeclMetadata(CodeGenModule &CGM,
2991 llvm::NamedMDNode *&GlobalMetadata,
2992 GlobalDecl D,
2993 llvm::GlobalValue *Addr) {
2994 if (!GlobalMetadata)
2995 GlobalMetadata =
2996 CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs");
2997
2998 // TODO: should we report variant information for ctors/dtors?
2999 llvm::Value *Ops[] = {
3000 Addr,
3001 GetPointerConstant(CGM.getLLVMContext(), D.getDecl())
3002 };
3003 GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
3004 }
3005
3006 /// For each function which is declared within an extern "C" region and marked
3007 /// as 'used', but has internal linkage, create an alias from the unmangled
3008 /// name to the mangled name if possible. People expect to be able to refer
3009 /// to such functions with an unmangled name from inline assembly within the
3010 /// same translation unit.
EmitStaticExternCAliases()3011 void CodeGenModule::EmitStaticExternCAliases() {
3012 for (StaticExternCMap::iterator I = StaticExternCValues.begin(),
3013 E = StaticExternCValues.end();
3014 I != E; ++I) {
3015 IdentifierInfo *Name = I->first;
3016 llvm::GlobalValue *Val = I->second;
3017 if (Val && !getModule().getNamedValue(Name->getName()))
3018 AddUsedGlobal(new llvm::GlobalAlias(Val->getType(), Val->getLinkage(),
3019 Name->getName(), Val, &getModule()));
3020 }
3021 }
3022
3023 /// Emits metadata nodes associating all the global values in the
3024 /// current module with the Decls they came from. This is useful for
3025 /// projects using IR gen as a subroutine.
3026 ///
3027 /// Since there's currently no way to associate an MDNode directly
3028 /// with an llvm::GlobalValue, we create a global named metadata
3029 /// with the name 'clang.global.decl.ptrs'.
EmitDeclMetadata()3030 void CodeGenModule::EmitDeclMetadata() {
3031 llvm::NamedMDNode *GlobalMetadata = 0;
3032
3033 // StaticLocalDeclMap
3034 for (llvm::DenseMap<GlobalDecl,StringRef>::iterator
3035 I = MangledDeclNames.begin(), E = MangledDeclNames.end();
3036 I != E; ++I) {
3037 llvm::GlobalValue *Addr = getModule().getNamedValue(I->second);
3038 EmitGlobalDeclMetadata(*this, GlobalMetadata, I->first, Addr);
3039 }
3040 }
3041
3042 /// Emits metadata nodes for all the local variables in the current
3043 /// function.
EmitDeclMetadata()3044 void CodeGenFunction::EmitDeclMetadata() {
3045 if (LocalDeclMap.empty()) return;
3046
3047 llvm::LLVMContext &Context = getLLVMContext();
3048
3049 // Find the unique metadata ID for this name.
3050 unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr");
3051
3052 llvm::NamedMDNode *GlobalMetadata = 0;
3053
3054 for (llvm::DenseMap<const Decl*, llvm::Value*>::iterator
3055 I = LocalDeclMap.begin(), E = LocalDeclMap.end(); I != E; ++I) {
3056 const Decl *D = I->first;
3057 llvm::Value *Addr = I->second;
3058
3059 if (llvm::AllocaInst *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) {
3060 llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D);
3061 Alloca->setMetadata(DeclPtrKind, llvm::MDNode::get(Context, DAddr));
3062 } else if (llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>(Addr)) {
3063 GlobalDecl GD = GlobalDecl(cast<VarDecl>(D));
3064 EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV);
3065 }
3066 }
3067 }
3068
EmitCoverageFile()3069 void CodeGenModule::EmitCoverageFile() {
3070 if (!getCodeGenOpts().CoverageFile.empty()) {
3071 if (llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu")) {
3072 llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov");
3073 llvm::LLVMContext &Ctx = TheModule.getContext();
3074 llvm::MDString *CoverageFile =
3075 llvm::MDString::get(Ctx, getCodeGenOpts().CoverageFile);
3076 for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) {
3077 llvm::MDNode *CU = CUNode->getOperand(i);
3078 llvm::Value *node[] = { CoverageFile, CU };
3079 llvm::MDNode *N = llvm::MDNode::get(Ctx, node);
3080 GCov->addOperand(N);
3081 }
3082 }
3083 }
3084 }
3085
EmitUuidofInitializer(StringRef Uuid,QualType GuidType)3086 llvm::Constant *CodeGenModule::EmitUuidofInitializer(StringRef Uuid,
3087 QualType GuidType) {
3088 // Sema has checked that all uuid strings are of the form
3089 // "12345678-1234-1234-1234-1234567890ab".
3090 assert(Uuid.size() == 36);
3091 const char *Uuidstr = Uuid.data();
3092 for (int i = 0; i < 36; ++i) {
3093 if (i == 8 || i == 13 || i == 18 || i == 23) assert(Uuidstr[i] == '-');
3094 else assert(isHexDigit(Uuidstr[i]));
3095 }
3096
3097 llvm::APInt Field0(32, StringRef(Uuidstr , 8), 16);
3098 llvm::APInt Field1(16, StringRef(Uuidstr + 9, 4), 16);
3099 llvm::APInt Field2(16, StringRef(Uuidstr + 14, 4), 16);
3100 static const int Field3ValueOffsets[] = { 19, 21, 24, 26, 28, 30, 32, 34 };
3101
3102 APValue InitStruct(APValue::UninitStruct(), /*NumBases=*/0, /*NumFields=*/4);
3103 InitStruct.getStructField(0) = APValue(llvm::APSInt(Field0));
3104 InitStruct.getStructField(1) = APValue(llvm::APSInt(Field1));
3105 InitStruct.getStructField(2) = APValue(llvm::APSInt(Field2));
3106 APValue& Arr = InitStruct.getStructField(3);
3107 Arr = APValue(APValue::UninitArray(), 8, 8);
3108 for (int t = 0; t < 8; ++t)
3109 Arr.getArrayInitializedElt(t) = APValue(llvm::APSInt(
3110 llvm::APInt(8, StringRef(Uuidstr + Field3ValueOffsets[t], 2), 16)));
3111
3112 return EmitConstantValue(InitStruct, GuidType);
3113 }
3114