Skip to content

Commit f49573d

Browse files
committed
weak globals that are const should get weak_odr linkage.
add a fixme about C++ const. llvm-svn: 78159
1 parent c0693bc commit f49573d

File tree

2 files changed

+35
-6
lines changed

2 files changed

+35
-6
lines changed

clang/lib/CodeGen/CodeGenModule.cpp

Lines changed: 19 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -870,7 +870,15 @@ void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) {
870870
}
871871

872872
GV->setInitializer(Init);
873-
GV->setConstant(D->getType().isConstant(Context));
873+
874+
// If it is safe to mark the global 'constant', do so now.
875+
GV->setConstant(false);
876+
if (D->getType().isConstant(Context)) {
877+
// FIXME: In C++, if the variable has a non-trivial ctor/dtor or any mutable
878+
// members, it cannot be declared "LLVM const".
879+
GV->setConstant(true);
880+
}
881+
874882
GV->setAlignment(getContext().getDeclAlignInBytes(D));
875883

876884
// Set the llvm linkage type as appropriate.
@@ -880,13 +888,18 @@ void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) {
880888
GV->setLinkage(llvm::Function::DLLImportLinkage);
881889
else if (D->hasAttr<DLLExportAttr>())
882890
GV->setLinkage(llvm::Function::DLLExportLinkage);
883-
else if (D->hasAttr<WeakAttr>())
884-
GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage);
885-
else if (!CompileOpts.NoCommon &&
891+
else if (D->hasAttr<WeakAttr>()) {
892+
if (GV->isConstant())
893+
GV->setLinkage(llvm::GlobalVariable::WeakODRLinkage);
894+
else
895+
GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage);
896+
} else if (!CompileOpts.NoCommon &&
886897
!D->hasExternalStorage() && !D->getInit() &&
887-
!D->getAttr<SectionAttr>())
898+
!D->getAttr<SectionAttr>()) {
888899
GV->setLinkage(llvm::GlobalVariable::CommonLinkage);
889-
else
900+
// common vars aren't constant even if declared const.
901+
GV->setConstant(false);
902+
} else
890903
GV->setLinkage(llvm::GlobalVariable::ExternalLinkage);
891904

892905
SetCommonAttributes(D, GV);

clang/test/CodeGen/global-init.c

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,8 +7,24 @@ int a;
77
int a = 242;
88
// CHECK: @a = global i32 242
99

10+
// This should get normal weak linkage.
11+
int c __attribute__((weak))= 0;
12+
// CHECK: @c = weak global i32 0
13+
14+
15+
16+
// Since this is marked const, it should get weak_odr linkage, since all
17+
// definitions have to be the same.
18+
// CHECK: @d = weak_odr constant i32 0
19+
const int d __attribute__((weak))= 0;
20+
21+
22+
23+
// NOTE: tentative definitions are processed at the end of the translation unit.
24+
1025
// This shouldn't be emitted as common because it has an explicit section.
1126
// rdar://7119244
1227
int b __attribute__((section("foo")));
1328

1429
// CHECK: @b = global i32 0, section "foo"
30+

0 commit comments

Comments
 (0)